Day11: [LeetCode中等] 61. 旋转链表
题源:
来自leetcode题库:
https://leetcode-cn.com/problems/rotate-list/
思路:
链表基本操作,唯一需要注意的是当要移动的位置量k是链表长度的倍数的时候,要单独处理一下。
代码:
dirty code凑合看吧
/**
* 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||k==0) return head;
int Len=0;
ListNode *p=head,*q=head;
while(p) {p=p->next;Len++;}
p=head;
if(k>=Len) k=k%Len;
if(k==0) return head;
for(int i=0;i<k;i++)
q=q->next;
while(q->next!=NULL){
p=p->next;
q=q->next;
}
auto res=p->next;
p->next=NULL;
q->next=head;
return res;
}
};