/**
* 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){
return head;
}
int length=1;
ListNode *former,*latter,*end;
end=head;
while(end->next!=NULL){
length++;
end=end->next;
}
k%=length;
if(!k){
return head;
}
former=head,latter=head;
for(int i=0;i<k;i++){
former=former->next;
}
while(former!=end){
former=former->next;
latter=latter->next;
}
end->next=head;
head=latter->next;
latter->next=NULL;
return head;
}
};
LeetCode - 61 Rotate List
最新推荐文章于 2024-05-15 22:45:44 发布