题目:
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL
解题:
方法1:模拟真实旋转过程:(可能会超时)
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head)
return nullptr;
if(!head->next)
return head;
for(int i=0;i<k;i++){
//尾巴
ListNode* tail = head;
ListNode* pre_tail = NULL;//尾巴前面1个
while(tail && tail->next){
pre_tail = tail;
tail = tail->next;
}
//旋转1步:
pre_tail->next = tail->next;
tail->next = head;
head = tail;
}
return head;
}
};
方法2:成环处理:
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
//代码鲁棒性
if(!head || !head->next || k == 0)
return head;
//找到尾结点
int len = 1;
ListNode* tail = head;
while(tail && tail->next){
len++;
tail = tail->next;
}
if(k==len || k%len == 0){
return head;
}
//成环
tail->next = head;
//成环后找出断点,拆开环
ListNode* cur = head;
ListNode* newtail = nullptr;
k = len-(k%len);
while(cur && k){
newtail = cur;
cur = cur->next;
k--;
}
newtail->next = nullptr;
return cur;
}
};