LeetCode 题解工作台

K 个一组翻转链表

给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。 k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。 示例 1: 输入: head = [1,…

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

困难 · 链表指针操作

bolt

答案摘要

我们可以根据题意,模拟整个翻转的过程。 首先,我们定义一个辅助函数 ,用于翻转一个链表。然后,我们定义一个虚拟头结点 ,并将其 指针指向 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。

k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

 

示例 1:

输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]

示例 2:

输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]

 

提示:
  • 链表中的节点数目为 n
  • 1 <= k <= n <= 5000
  • 0 <= Node.val <= 1000

 

进阶:你可以设计一个只用 O(1) 额外内存空间的算法解决此问题吗?

lightbulb

解题思路

方法一:模拟

我们可以根据题意,模拟整个翻转的过程。

首先,我们定义一个辅助函数 reverse\textit{reverse},用于翻转一个链表。然后,我们定义一个虚拟头结点 dummy\textit{dummy},并将其 next\textit{next} 指针指向 head\textit{head}

接着,我们遍历链表,每次遍历 kk 个节点,若剩余节点不足 kk 个,则不进行翻转。否则,我们将 kk 个节点取出,然后调用 reverse\textit{reverse} 函数翻转这 kk 个节点。然后将翻转后的链表与原链表连接起来。继续遍历下一个 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
28
29
30
31
32
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        def reverse(head: Optional[ListNode]) -> Optional[ListNode]:
            dummy = ListNode()
            cur = head
            while cur:
                nxt = cur.next
                cur.next = dummy.next
                dummy.next = cur
                cur = nxt
            return dummy.next

        dummy = pre = ListNode(next=head)
        while pre:
            cur = pre
            for _ in range(k):
                cur = cur.next
                if cur is None:
                    return dummy.next
            node = pre.next
            nxt = cur.next
            cur.next = None
            pre.next = reverse(node)
            node.next = nxt
            pre = node
        return dummy.next
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidates who focus on pointer manipulation and recursion will likely show a strong understanding of the problem's core pattern.

  • question_mark

    Look for candidates who efficiently reverse nodes without excessive memory allocation or recursion depth.

  • question_mark

    Candidates should be able to identify edge cases, such as when the number of nodes is less than k, and handle them appropriately.

warning

常见陷阱

外企场景
  • error

    Failing to properly reverse nodes and inadvertently breaking the list structure can lead to lost or corrupted data.

  • error

    Mismanaging the list when fewer than k nodes remain will result in incorrect answers or infinite loops.

  • error

    Candidates may struggle with recursion depth limitations in cases with long lists, especially when not using iteration.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handling different k values, including small values (k = 1) and larger values relative to list size.

  • arrow_right_alt

    Implementing the solution iteratively instead of recursively for performance optimization in cases with large n.

  • arrow_right_alt

    Reversing nodes in different patterns, such as reversing every other k nodes, instead of all k nodes consecutively.

help

常见问题

外企场景

K 个一组翻转链表题解:链表指针操作 | LeetCode #25 困难