leetcode 61. Rotate List

来源:互联网 发布:淘宝商家阶层 编辑:程序博客网 时间:2024/04/29 06:21

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.



class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if (k == 0) return head; ListNode*p = head; int len = 0; while (p != NULL) { p = p->next; len++; } if (len == 0||len==1) return head; k = k%len; if (k == 0) return head; p = head; int kk = 1; while (kk != len - k) { p = p->next; kk++; } ListNode*p1 = p->next, *p2 = p->next; while (p1->next != NULL) p1 = p1->next; p1->next = head; p->next = NULL; head = p2; return head; } };

accepted


0 0
原创粉丝点击