[LeetCode] Rotate List
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
.
Linked List Two Pointers
class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(head == NULL) return NULL; ListNode * p = head; int len = 0; ListNode * seg1Last = NULL; ListNode * seg2Last = NULL; ListNode * seg2Head = NULL; while(p != NULL) { if(p-> next == NULL) seg2Last = p; len ++; p = p->next; } k = k % len; if(k == 0) return head; k = len - k; p = head; while(--k) { p = p->next; } seg1Last = p; seg2Head = p -> next; seg2Last -> next = head; seg1Last -> next = NULL; return seg2Head; } };