61. 旋转链表

自己做
解:截取拼接

cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
ListNode *p = head, *q = head, *r = head;
int l = 0; //链表长
if(head == nullptr || head->next == nullptr) //没有移动空间
return head;
while(p != nullptr){ //计算链表长
p = p -> next;
l++;
}
p = head; //归位p
//调整k
k %= l;
if(k == 0) //为0则不移动
return head;
for(int i = 0; i < k; i++) //q、r包含k个元素
r = r->next;
if(k > 0)
q = p->next;
while(r->next != nullptr){ //使r指向尾部
p = q;
r = r->next;
q = q->next;
}
p->next = nullptr;
r->next = head;
return q;
}
};
