题目描述
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
一、算法描述
对于旋转链表直接使用暴力解法,使时间复杂度为
O
(
N
2
)
O(N^2)
O(N2),并且在Leetcode提交时会显示超时。所以一种降低时间复杂度的算法为,将链表的尾节点与头节点相连,构成循环链表,进行旋转操作时候并不需要真正移动每一个链表中的元素,而是将移动次数转为计算尾节点的位置,具体公式为
i
n
d
e
x
=
l
e
n
g
t
h
−
1
−
k
%
l
e
n
g
t
h
index=length-1-k\%length
index=length−1−k%length
当找到尾节点,则需要建立新的头节点,并且将循环链表断开。
result=index.next
index.next=null
二、JAVA实现
public ListNode rotateRight(ListNode head, int k){
if (head==null||head.next==null) return head;
int n=1;
ListNode temp=head;
while (temp.next!=null){
temp=temp.next;
n++;
}
int last=k%n;
if (last==0) return head;//移动链表的整数倍
temp.next=head;
temp=head;
for (int i=0;i<n-1-last;i++)
temp=temp.next;
ListNode result=temp.next;
temp.next=null;
return result;
}