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
.
Code:
<span style="font-size:14px;">/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (head == NULL || head->next == NULL) return head;
int length = 0;
ListNode *copy = head, *temp;
while (copy != NULL) {
length++;
copy = copy->next;
}
k = k%length;
if (k == 0) return head;
copy = head;
for (int i = 0; i < length-k-1; ++i)
copy = copy->next;
temp = copy->next;
copy->next = NULL;
copy = temp;
while (copy != NULL && copy->next != NULL)
copy = copy->next;
copy->next = head;
return temp;
}
};</span>