61. 旋转链表
题目描述
给你一个链表的头节点 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
- 0 <= k <= 2 * 109
解题方案
- C 先闭合为环再拆分
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k) {
struct ListNode* temp = head;
if (NULL == temp || NULL == temp->next || 0 == k) {
return temp;
}
int length = 1;
while (temp->next) {
temp = temp->next;
length++; // 计算长度
}
temp->next = head; // 闭合为环
k = length - k % length; // 计算找到新的头节点要移动距离
while (k--) {
temp = temp->next;
}
struct ListNode* ptr = temp->next;
temp->next = NULL; // 拆分环
return ptr;
}
复杂度分析
时间复杂度为 O(n)。
空间复杂度为 O(1)。