题目链接
题目描述
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k个位置。
示例 1:

输入: head = [1,2,3,4,5], k = 2
输出: [4,5,1,2,3]
示例 2:

输入: head = [0,1,2], k = 4
输出: [2,0,1]
提示:
- 链表中节点的数目在范围
[0, 500]内 -100 <= Node.val <= 100-
解题思路
方法一:截断重组
/*** 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==nullptr||head->next==nullptr||k==0){return head;}// 统计结点个数int len = 0;ListNode* cur = head;while(cur){len++;cur = cur->next;}// 套圈情况if(k%len==0){return head;}// cur指向结果的最后一个结点k = len - k%len - 1;cur = head;while(k--){cur = cur->next;}// 返回头节点为下一个节点ListNode* res = cur->next;cur->next = nullptr;// 链接两个链表cur = res;while(cur&&cur->next){cur = cur->next;}cur->next = head;return res;}};
时间复杂度 O(2n)
-
方法一:闭合为环
/** * 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==nullptr||head->next==nullptr||k==0){ return head; } int len = 1; ListNode* cur = head; while(cur->next){ len++; cur = cur->next; } cur->next = head; cur = head; k = len-(k%len)-1; while(k--){ cur = cur->next; } head = cur->next; cur->next = nullptr; return head; } }; 时间复杂度 O(2n)
- 空间复杂度 O(1)
