Leetcode - 61. 旋转链表
给你一个链表的头节点
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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解1 2021/9/9 O(n)
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __repr__(self):
return '{}'.format(self.val) + ('' if (self.next==None) else (self.next.__repr__()))
def rotateRight(head: ListNode, k: int) -> ListNode:
# 首先,链表比如长3,挪4和挪1一个效果
# 其次,说白了就是把后面的k个数拿到前面来
len=0
tmp=head
# 把最后一个顺便记下来
last=head
while tmp:
len+=1
if tmp.next==None: last=tmp
tmp=tmp.next
### 错误 - 1
if len==0: return head
### 错误 - 1
k%=len
if len==1 or k==0: return head
dummy=ListNode(-1,head)
i=len-k-1
tmp=head
while i>0:
tmp=tmp.next
i-=1
dummy.next=tmp.next
last.next=head
tmp.next=None
return dummy.next
if __name__ == '__main__':
# [4,5,1,2,3]
head = [1, 2, 3, 4, 5];k = 2
lh=ListNode(1,ListNode(2,ListNode(3,ListNode(4,ListNode(5)))))
print(rotateRight(lh,k))
# [2,0,1]
head = [0, 1, 2];k = 4
lh=ListNode(0,ListNode(1,ListNode(2)))
print(rotateRight(lh,k))
lh=ListNode(1,ListNode(2))
print(rotateRight(lh,2))
lh=ListNode(1,ListNode(2))
print(rotateRight(lh,0))
lh=ListNode(1,ListNode(2))
print(rotateRight(lh,1))
lh=ListNode(1)
print(rotateRight(lh,1))
lh=ListNode(1)
print(rotateRight(lh,3))
### 错误
# 1
# 节点数∈[0,500],链表还可能是空的,注意限制条件的解读
lh=None
print(rotateRight(lh,0))


浙公网安备 33010602011771号