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
.
Idea: get the length of length - k, then put the list in front. Then it is done.
/**
* 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 == nullptr || head-> next == nullptr || k <= 0) return head;
int length = 1;
ListNode *p = head;
ListNode *q = p;
while(p->next != nullptr)
{
length++;
p = p->next;
}
int times = k % length;
if(times == 0) return head;
ListNode *temp = new ListNode(-1);
temp->next = head;
int i = 0;
ListNode *r = head;
while(i++ < length - times)
{
r = q;
q = q->next;
}
temp->next = q;
p->next = head;
r->next = nullptr;
return temp->next;
}
};