Description
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
思路
非常直观的思路,就是先遍历到最后,连接成为一个循环链表,然后双指针移动一定的步数,断开循环链表返回头部。
一点优化
注意到0<=k<=2∗1090 <= k <= 2 * 10^90<=k<=2∗109,Nodes∈[0,500]Nodes\in[0,500]Nodes∈[0,500],绕着链表转圈肯定是无用的。所以直接简化步骤,trueK=k%length
,length在遍历到尾节点的时候计数得到。
一定的步数是多少?
不是上文的trueK
而是length-trueK
。为什么?画个图就知道了。反正我试了很多次才发现这个思维盲点。。。因为这个方法移动的是头节点指针,而不是题目描述的移动所有节点。
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if head==None:
return None
if k==0:
return head
cur=head
length=1
while cur.next:
length+=1
cur=cur.next
#print(length)
truemove=length-(k)%length
#Connect
cur.next=head
pre=head
aft=cur
#print(truemove)
for _ in range(truemove):
pre=pre.next
aft=aft.next
aft.next=None
return pre
执行用时:40 ms, 在所有 Python3 提交中击败了83.53%的用户
内存消耗:14.9 MB, 在所有 Python3 提交中击败了35.90%的用户
还行。打卡。