61. 旋转链表

Difficulty
Medium
Tags
链表
URL
https://leetcode.cn/problems/rotate-list/
Star
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
示例 1:
notion imagenotion image
输入:head = [1,2,3,4,5], k = 2 输出:[4,5,1,2,3]
示例 2:
notion imagenotion image
输入:head = [0,1,2], k = 4 输出:[2,0,1]
提示:
  • 链表中节点的数目在范围 [0, 500]
  • 100 <= Node.val <= 100
  • 0 <= k <= 2 * 109
通过次数247,758提交次数594,352

法1

思路
计算倒数 k 个节点 转化为计算正数 length-k 个节点,然后找到之后,接到头节点
题解
# 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 head is None: return head length = 0 cur = head while cur: cur = cur.next length += 1 k = k % length # k = 0 表示不用翻转 if k == 0: return head # 找倒数第二个节点 = 找正数 第 length - k 个 节点 k = length - k count = 1 cur = head while cur: if count == k: break count += 1 cur = cur.next # 把后半段保存一下,再断开 nxt = cur.next cur.next = None res = nxt # 找到后半段的尾巴,接到 head 上 while nxt and nxt.next: nxt = nxt.next nxt.next = head return res