给你一个链表的头节点 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
Python实现
把链表连接成一个换,然后需要找到规律(n-k)%n即环形链表需要断开的位置,如果能找到这个规律就能写出来了。
# 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: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head or not head.next:
return head
n=1
cur = head
while cur.next:
cur = cur.next
n+=1
k = (n-k)%n
cur.next = head
while k:
cur = cur.next
k-=1
res = cur.next
cur.next = None
return res