中等
1.1旋转链表
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-list
先遍历一遍整个链表,计数的同时把链表变为循环链表,这样方便后期将链表断开,之后根据k和count计算断开位置。
ListNode* rotateRight(ListNode* head, int k) {
if(head == nullptr || head->next == nullptr)
return head;
ListNode* p = head;
ListNode* q = p;
int count = 1;
while (q->next){
q = q->next;
count++;
}
q->next = p; //循环单向列表
k %= count;
k = count - k; //计算断开位置,即断开后的头结点
ListNode* last = nullptr; //断开后的尾结点
for (int i = 0; i < k; ++i) {
last = p;
p = p->next;
}
if(last){
last->next = nullptr;
return p;
} else{
q->next = nullptr;
return p;
}
}