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
.
Runtime: 12ms.
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* rotateRight(ListNode* head, int k) { 12 if(!head || !head->next) return head; 13 14 // first find the (n - k % n)th element 15 ListNode* move = head; 16 int count = 1; 17 while(move->next) { 18 count++; 19 move = move->next; 20 } 21 ListNode* endNode = move; 22 23 k %= count; 24 move = head; 25 int index = 0; 26 while(index++ < k) 27 move = move->next; 28 29 ListNode* current = head; 30 while(move->next) { 31 move = move->next; 32 current = current->next; 33 } 34 endNode->next = head; 35 head = current->next; 36 current->next = NULL; 37 38 return head; 39 } 40 };