61. 旋转链表

自己做
解:截取拼接

/*** 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//调整kk %= 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;}
};
