给你一个链表的头节点 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 * 10^9
Python 解答:
# 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 not head or not k:
return head
p = head
lens = 0
pre, seq = None, None
while p:
lens += 1
seq = p
p = p.next
k = lens - k % lens
if k == lens:
return head
p = head
while k > 0:
pre = p
p = p.next
k -= 1
pre.next = None
seq.next = head
return p
留言