LeetCode 题解工作台

旋转链表

给你一个链表的头节点 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] 提示: 链表中节点的数目在…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 链表指针操作

bolt

答案摘要

我们先判断链表节点数是否小于 ,如果是,直接返回 即可。 否则,我们先统计链表节点数 ,然后将 对 取模,得到 的有效值。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个链表的头节点 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
lightbulb

解题思路

方法一:快慢指针 + 链表拼接

我们先判断链表节点数是否小于 22,如果是,直接返回 headhead 即可。

否则,我们先统计链表节点数 nn,然后将 kknn 取模,得到 kk 的有效值。

如果 kk 的有效值为 00,说明链表不需要旋转,直接返回 headhead 即可。

否则,我们用快慢指针,让快指针先走 kk 步,然后快慢指针同时走,直到快指针走到链表尾部,此时慢指针的下一个节点就是新的链表头节点。

最后,我们将链表拼接起来即可。

时间复杂度 O(n)O(n),其中 nn 是链表节点数,空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 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 or head.next is None:
            return head
        cur, n = head, 0
        while cur:
            n += 1
            cur = cur.next
        k %= n
        if k == 0:
            return head
        fast = slow = head
        for _ in range(k):
            fast = fast.next
        while fast.next:
            fast, slow = fast.next, slow.next

        ans = slow.next
        slow.next = None
        fast.next = head
        return ans
speed

复杂度分析

指标
时间complexity is O(n) because the list is traversed to find its length and then to relocate pointers. Space complexity is O(1) since no extra structures are needed beyond a few pointers.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect correct pointer updates without creating cycles or losing nodes.

  • question_mark

    Check handling of k values larger than the list length.

  • question_mark

    Look for proper empty list and single-node edge case handling.

warning

常见陷阱

外企场景
  • error

    Not using modulo for k, leading to extra unnecessary rotations.

  • error

    Incorrectly updating the tail node, causing cycles or null references.

  • error

    Failing to handle lists with length 0 or 1 properly.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Rotate list to the left by k positions instead of right.

  • arrow_right_alt

    Rotate a doubly linked list using similar pointer adjustments.

  • arrow_right_alt

    Rotate only a subsegment of the list rather than the entire list.

help

常见问题

外企场景

旋转链表题解:链表指针操作 | LeetCode #61 中等