给你一个链表的头节点
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
/**
一瓶酒一支烟,一道破题写一天(无能狂怒中...
官方解法:闭合为环
时间复杂度O(n),空间复杂度O(1)
**/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null||k==0||head.next==null) return head;//空、只有一个节点、向右移动0,返回本身
ListNode cur=head,newhead=null;//申请一个当前节点和一个新头节点的记录节点
int count=0;//存储链表长度,从0开始算
while(cur!=null&&cur.next!=null){//判断cur.next非空是为了得到最后一个节点后续空节点
count++;
cur=cur.next;
}
k=k%(count+1);//链表实际长度需要count+1。如果右移是总长度的倍数,即模(链表长度)为0,则不移
if(k==0) return head;
cur.next=head;//否则将尾部与头节点相连形成环
int left=0;
int right=count-k;//翻转后链表的最后一个点的位置
cur=head;
while(left<right&&cur!=null){//找到翻转链表最后一个点断开环
cur=cur.next;
left++;
}
newhead=cur.next;//记录新链表最后一个节点的下一位置作为新头节点
cur.next=null;//断开环
return newhead;
}
}
/**
题解来自https://leetcode-cn.com/problems/rotate-list/solution/fu-xue-ming-zhu-wen-ti-chai-fen-fen-xian-z4dr/
比官方解法慢,内存消耗小一丢丢。感觉比官方解法思路灵活,由于需要求链表长度,这样做反倒鸡肋
但是我很喜欢这个解法!
**快慢指针:
快慢指针间距为k-1。快指针先出发k步,慢指针再从起点开始,与快指针同时同速走
那么,当快指针到达链表结尾时,慢指针刚好与快指针中间间隔k-1个数
此时,慢指针所在处刚好是新链表的末尾,将其断开,指向新头节点
快指针所在处是与旧无需翻转链表的连接处,指向旧头节点**
**/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null||head.next==null||k==0)return head;
ListNode fast=head,slow=head,newhead=null,temp=head;
int count=0;
while(temp!=null) {//用来计算链表长度
temp=temp.next;
count++;
}
if((k=k%count)==0)return head;//模(链表长度)=0说明不翻转
for(int i=0;i<k;i++) {
fast=fast.next;//快指针先走k步
}
while(fast!=null&&fast.next!=null) {//快指针肯定比慢指针先到结尾,常规边界判断
fast=fast.next;
slow=slow.next;//一起走
}
fast.next=head;//连接无需翻转的旧链表头
newhead=slow.next;//断开处指向新头节点
slow.next=null;//断开
return newhead;
}
}