61. Rotate List
Medium
Given the head of a linked list, rotate the list to the right by k places.
Example 1:

Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3]
Example 2:

Input: head = [0,1,2], k = 4 Output: [2,0,1]
Constraints:
- The number of nodes in the list is in the range
[0, 500]. -100 <= Node.val <= 1000 <= k <= 2 * 109
解法1:
先将链表首尾相连,然后从尾往后移动n-k步就到了新链表的前一个位置,断开链表并返回新链表的位置即可。
/**
* 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) return nullptr;
ListNode *p = head;
int cnt = 1;
while (p->next) {
p = p->next;
cnt++;
}
k %= cnt;
p->next = head;
for (int i = 0; i < cnt - k; i++) p = p->next;
head = p->next;
p->next = nullptr;
return head;
}
};
本文解析如何使用O(n)时间复杂度解决链表旋转问题,通过节点计数和连接首尾巧妙简化操作。理解链表旋转的原理并学习高效算法实现。
186

被折叠的 条评论
为什么被折叠?



