Given a list, rotate the list to the right by k places, where k is
non-negative.Given 1->2->3->4->5 and k = 2, return 4->5->1->2->3.
1、首先要理解这个旋转的意义。
就是倒着数k个node,从那开始到结尾和之前那部分对调,那个例子就是,4->5拿前面来,1->2->3拿后面去。
2.当k大于链的长度len时,k=k%len;
3.用faster/slower双指针解决(看到这种linkedlist,倒着数数的,要条件反射)
(1)faster指针先走k步;
(2)接着slower指针和faster指针一起走,直到faster->next==NULL为止;、
此时,sower指针指向倒数第k个数的前一个数。
(3)将head赋给faster->next,slower->next赋给新的头指针,slower->next赋为NULL。
参考:Rotate List leetcode java
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head: the list
* @param k: rotate to the right k places
* @return: the list after rotation
*/
ListNode *rotateRight(ListNode *head, int k) {
// write your code here
if(head==NULL){
return NULL;
}
int len=0;
ListNode *p=head;
while(p){
p=p->next;
len++;
}
ListNode *faster=head;
ListNode *lower=head;
int i=0;
k=k%len;
while(i<k){
faster=faster->next;
i++;
}
while(faster->next!=NULL){
faster=faster->next;
lower=lower->next;
}
faster->next=head;
ListNode *new_head=lower->next;
lower->next=NULL;
return new_head;
}
};