LeetCode 题解工作台
两两交换链表中的节点
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。 示例 1: 输入: head = [1,2,3,4] 输出: [2,1,4,3] 示例 2: 输入: head = [] 输出: [] 示例 3: 输入: head …
2
题型
10
代码语言
3
相关题
当前训练重点
中等 · 链表指针操作
答案摘要
我们可以通过递归的方式实现两两交换链表中的节点。 递归的终止条件是链表中没有节点,或者链表中只有一个节点,此时无法进行交换,直接返回该节点。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
输入:head = [1,2,3,4] 输出:[2,1,4,3]
示例 2:
输入:head = [] 输出:[]
示例 3:
输入:head = [1] 输出:[1]
提示:
- 链表中节点的数目在范围
[0, 100]内 0 <= Node.val <= 100
解题思路
方法一:递归
我们可以通过递归的方式实现两两交换链表中的节点。
递归的终止条件是链表中没有节点,或者链表中只有一个节点,此时无法进行交换,直接返回该节点。
否则,我们递归交换链表 ,记交换后的头节点为 ,然后我们记 的下一个节点为 ,然后令 指向 ,而 指向 ,最后返回 。
时间复杂度 ,空间复杂度 ,其中 是链表的长度。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head
t = self.swapPairs(head.next.next)
p = head.next
p.next = head
head.next = t
return p
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They want to see whether you can swap the head pair without writing a fragile special case, which usually points to using a dummy node.
- question_mark
They are checking if you understand pointer-update order, especially saving the node after the current pair before rewiring.
- question_mark
If they mention recursion, they want you to compare cleaner expression against call-stack cost for this exact pair-swapping list problem.
常见陷阱
外企场景- error
Updating first.next or second.next before saving the rest of the list, which disconnects the remaining nodes.
- error
Moving the traversal pointer to the wrong node after a swap, causing skipped pairs or infinite loops.
- error
Swapping node values instead of node links, which violates the problem requirement even if the output values look correct.
进阶变体
外企场景- arrow_right_alt
Swap nodes in groups of k, where this problem becomes the k = 2 version of linked-list group reversal.
- arrow_right_alt
Swap pairs recursively, then rewrite the same logic iteratively to remove stack usage.
- arrow_right_alt
Handle a doubly linked list version where both next and prev links must stay consistent after each pair swap.