给你一个链表的头节点 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
方案
源自天池平台
# 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:
return None
length= 0
temp = head
while temp.next:
length += 1
temp = temp.next
temp.next = head
k = k% (length - 1)
temp = head
for i in range(length - k):
temp = temp.next
temp.next = None
return head
原理是通过删除链表关键节点,从而实现
如1-2-3-4-5,K=2
从后面数2个,即将3-4的链接剪断,首尾5和1再建立链接。
1-2-3 4-5剪断
4-5-1-2-3首位相连
来源:天池