leetCode61. 旋转链表
题目思路:见如图所示
代码展示
/*** 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) {if(!head) return head;int n; // 找出链表长度ListNode* tail; // 找到尾结点for(auto p = head; p; p = p->next){tail = p;n++;}// k的值可能大于n,我们要去取有效的k %= n;if(k == 0) return head;auto p = head;for(int i = 0; i < n - k - 1; i++) p = p->next;tail->next = head;head = p->next;p->next = nullptr;return head;}
};