LeetCode_Rotate List
1620 ワード
Given a list, rotate the list to the right by k places, where k is non-negative.
For example: Given
return
For example: Given
1->2->3->4->5->NULL
and k = 2
, return
4->5->1->2->3->NULL
. /**
* 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) {
//head is NULL
if(!head){
return head;
}
ListNode *temp=head;
ListNode *pretemp=NULL;
ListNode *rotatePos=NULL;
ListNode *preRotatePos=NULL;
//calculate listLen
int listLen=0;
while(temp){
temp=temp->next;
listLen++;
}
//calculate the real num need to rotate
int t=k%listLen;
if(!t){
return head;
}
temp=head;
//find the kth ListNode from tail
int i=0;
while(i<t&&temp){
i++;
temp=temp->next;
}
//the list length is greater then k
if (temp){
rotatePos=head;
while(temp){
pretemp=temp;
temp=temp->next;
preRotatePos=rotatePos;
rotatePos=rotatePos->next;
}
preRotatePos->next=NULL;
pretemp->next=head;
head=rotatePos;
}
return head;
}
};