/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!head) return NULL;
if (k==0) return head;
ListNode *temp=head, *end=NULL, *res=head;
int len=0;
while (temp) {
len++;
end=temp;
temp=temp->next;
}
if (k%len==0) return head;
int rest=len-k%len-1;
if (rest>=0) {
temp=head;
while(rest>0) {
rest--;
temp=temp->next;
}
res=temp->next;
temp->next=NULL;
end->next=head;
}
return res;
}
};
Rotate List
最新推荐文章于 2021-02-22 00:22:52 发布