题意
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.
解法
注意点:对于超出链表长度的k,取余数
实现
/**
* 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 || k <= 0) return head;
int idx = 1;
ListNode* fast = head;
//get length
while(fast->next != NULL){
++idx;
fast = fast->next;
}
k = k % idx;
if(k == 0) return head;
fast = head;
ListNode* slow = head;
ListNode* pre = NULL;
idx = 1;
while(idx < k && fast->next != NULL){
++idx;
fast = fast->next;
}
while(fast->next != NULL){
fast = fast->next;
pre = slow;
slow = slow->next;
}
pre->next = NULL;
fast->next = head;
head = slow;
return head;
}
};