61 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.
Solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int length(ListNode* head) {
int i = 0;
ListNode *p = head;
while ( p != NULL ) {
p = p->next;
i += 1;
}
return i;
}
ListNode* Nth(ListNode* head, int n) {
ListNode *p = head;
for ( int i = 1; i <= n-1; i++ ) p = p->next;
return p;
}
ListNode* rotateRight(ListNode* head, int k) {
int n = length(head);
if ( n == 0 ) return head;
k = k%n;
if ( k == 0 ) return head;
ListNode *p1 = Nth(head, n-k), *ptail = Nth(head, n);
ListNode *p2 = p1->next;
p1->next = NULL;
ptail->next = head;
return p2;
}
};
Notes
Take of the special case:
- n == 0
- k == 0
p1 == ptail p2 == NULL