LeetCode 题解工作台
K 个一组翻转链表
给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。 k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。 示例 1: 输入: head = [1,…
2
题型
8
代码语言
3
相关题
当前训练重点
困难 · 链表指针操作
答案摘要
我们可以根据题意,模拟整个翻转的过程。 首先,我们定义一个辅助函数 ,用于翻转一个链表。然后,我们定义一个虚拟头结点 ,并将其 指针指向 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
给你链表的头节点 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 <= 50000 <= Node.val <= 1000
进阶:你可以设计一个只用 O(1) 额外内存空间的算法解决此问题吗?
解题思路
方法一:模拟
我们可以根据题意,模拟整个翻转的过程。
首先,我们定义一个辅助函数 ,用于翻转一个链表。然后,我们定义一个虚拟头结点 ,并将其 指针指向 。
接着,我们遍历链表,每次遍历 个节点,若剩余节点不足 个,则不进行翻转。否则,我们将 个节点取出,然后调用 函数翻转这 个节点。然后将翻转后的链表与原链表连接起来。继续遍历下一个 个节点,直到遍历完整个链表。
时间复杂度 ,其中 为链表的长度。空间复杂度 。
# 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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.