给你一个链表的头节点 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]
链接:https://leetcode-cn.com/problems/rotate-list
class Solution:
def rotateRight(self, head:ListNode, k:int):
if not head or not head.next:return head
length = 0
cur = head
while cur:
length += 1
cur = cur.next
k = k%length
if k==0:return head
slow, fast = head, head
while fast.next:
slow = slow.next
fast = fast.next
Newhead = slow.next
slow.next = None
fast.next = head
return Newhead
Leetcode 61 旋转链表 (每日一题 20210723)
最新推荐文章于 2024-07-12 10:00:00 发布