LeetCode 题解工作台

两两交换链表中的节点

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。 示例 1: 输入: head = [1,2,3,4] 输出: [2,1,4,3] 示例 2: 输入: head = [] 输出: [] 示例 3: 输入: head …

category

2

题型

code_blocks

10

代码语言

hub

3

相关题

当前训练重点

中等 · 链表指针操作

bolt

答案摘要

我们可以通过递归的方式实现两两交换链表中的节点。 递归的终止条件是链表中没有节点,或者链表中只有一个节点,此时无法进行交换,直接返回该节点。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

 

示例 1:

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

示例 2:

输入:head = []
输出:[]

示例 3:

输入:head = [1]
输出:[1]

 

提示:

  • 链表中节点的数目在范围 [0, 100]
  • 0 <= Node.val <= 100
lightbulb

解题思路

方法一:递归

我们可以通过递归的方式实现两两交换链表中的节点。

递归的终止条件是链表中没有节点,或者链表中只有一个节点,此时无法进行交换,直接返回该节点。

否则,我们递归交换链表 head.next.nexthead.next.next,记交换后的头节点为 tt,然后我们记 headhead 的下一个节点为 pp,然后令 pp 指向 headhead,而 headhead 指向 tt,最后返回 pp

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n),其中 nn 是链表的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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
speed

复杂度分析

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

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

两两交换链表中的节点题解:链表指针操作 | LeetCode #24 中等