旋转链表(leetcode61)c++
https://leetcode-cn.com/problems/rotate-list/
//先将链表闭合成环
//然后找到相应的位置断开这个环,确定新的链表头和链表尾
//1. 找到旧的尾部并将其与链表头相连,整个链表闭合成环,同时计算出链表的长度 n。
//2. 找到新的尾部,第 (n - k % n - 1) 个节点 ,新的链表头是第 (n - k % n) 个节点。
//3. 断开环 new_tail->next = None,并返回新的链表头 new_head。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
//先将链表闭合成环
//然后找到相应的位置断开这个环,确定新的链表头和链表尾
//1. 找到旧的尾部并将其与链表头相连,整个链表闭合成环,同时计算出链表的长度 n。
//2. 找到新的尾部,第 (n - k % n - 1) 个节点 ,新的链表头是第 (n - k % n) 个节点。
//3. 断开环 new_tail->next = None,并返回新的链表头 new_head。
ListNode *old_tail,*new_tail;
ListNode *old_head,*new_head;
int len=0;
old_head=head;
old_tail=head;
if(old_tail==nullptr){
return old_head;
}
len++;
//----[1]----
while(old_tail!=nullptr && old_tail->next!=nullptr){
len++;
old_tail=old_tail->next;
}
old_tail->next=old_head;
//~
//----[2]----
int last=0; int first=0;
new_tail=old_head;
new_head=old_head;
while(last!=len-k%len-1){
if(new_tail->next!=nullptr){
new_tail=new_tail->next;
}
last++;
}
while(first!=len-k%len){
if(new_head->next!=nullptr){
new_head=new_head->next;
}
first++;
}
//~
//----[3]----
new_tail->next=nullptr;
return new_head;
//~
}
};