LeetCode 24 两两交换链表中的节点:递归与迭代两种指针重排实现(doocs/leetcode 题解详解)

原创2026-10-15 17:36:311,637 阅读
文章标签:示例工程

LeetCode 24 两两交换链表中的节点:递归与迭代两种指针重排实现(doocs/leetcode 题解详解)

本文以 doocs/leetcode 仓库中 LeetCode 24 题解文档 为主体,完整覆盖题目约束、递归与迭代两种解法的核心思路、多语言实现与复杂度分析。读完后你将掌握:在不修改节点值的前提下如何通过"改指针"完成两两交换、递归中 head.next.next 子问题如何归约、迭代中 dummy 头与 pre/cur 双指针的精确写序,以及两种方案在空间开销上的本质差异。

示例 1:输入 [1,2,3,4] 两两交换后得到 [2,1,4,3] 的链表示意图

题目描述与约束

给定一个链表,要求两两交换相邻的节点并返回新的头节点。关键限制是:不能修改节点内部的值(val),只能交换节点本身。这意味着交换的本质是重排 next 指针,而不是交换数据。

题目给出的示例:

示例 输入 输出 说明
1 head = [1,2,3,4] [2,1,4,3] 第 1、2 节点互换,第 3、4 节点互换
2 head = [] [] 空链表直接返回
3 head = [1] [1] 单节点无法成对,原样返回
4 head = [1,2,3] [2,1,3] 最后一落单的节点保持不动

约束条件:

  • 节点数量范围 [0, 100];
  • 每个节点的值满足 0 <= Node.val <= 100。

由于节点数上限仅 100,任何正确的指针重排都能通过测试;真正需要想清楚的是换链顺序——先翻转第一对再处理剩余部分时,很容易丢掉后续的节点。

解法一:递归

核心思路

递归的关键观察是:交换完当前一对后,从第 3 个节点开始的剩余子链表是同一个问题。因此:

  1. 递归终止条件:链表为空或只剩一个节点时,无法构成一对,直接返回该节点;
  2. 归约:否则先递归交换 head.next.next 开头的后缀,得到后缀交换后的头节点 t;
  3. 接线:令 p = head.next,把 p.next 指向 head,把 head.next 指向 t,最后返回 p(它成为当前这一对交换后的新头)。

以 head = [1,2,3,4] 手工推演一遍:

  • 调用 swapPairs(1),不满足终止条件,先递归 swapPairs(3);
  • swapPairs(3) 中 3 有后继 4,继续递归 swapPairs(nil),返回 nil;
  • 回到 3,4 这一层:t = nil,p = 4,执行 4->3、3->nil,返回 4;
  • 回到 1,2 这一层:t = 4,p = 2,执行 2->1、1->4,返回 2;
  • 最终链表为 2->1->4->3,与示例一致。

注意递归里必须先拿到 t 再改 head.next,否则一旦先执行 p.next = head,head 原来的后继就断链了,head.next.next 会指错。

代码实现

仓库中 Solution.py、Solution.cpp、Solution.go、Solution.ts 等均采用该递归方案,核心实现如下。

Python3

# 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

Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode t = swapPairs(head.next.next);
        ListNode p = head.next;
        p.next = head;
        head.next = t;
        return p;
    }
}

C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (!head || !head->next) {
            return head;
        }
        ListNode* t = swapPairs(head->next->next);
        ListNode* p = head->next;
        p->next = head;
        head->next = t;
        return p;
    }
};

Go

func swapPairs(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}
	t := swapPairs(head.Next.Next)
	p := head.Next
	p.Next = head
	head.Next = t
	return p
}

TypeScript

function swapPairs(head: ListNode | null): ListNode | null {
    if (!head || !head.next) {
        return head;
    }
    const t = swapPairs(head.next.next);
    const p = head.next;
    p.next = head;
    head.next = t;
    return p;
}

此外,文档还收录了 JavaScript、C#、Rust、Ruby 等版本。其中 Rust 版本由于所有权语义的限制,实际采用的是 dummy 头 + 循环的写法,Ruby 版本同理,这也侧面说明"递归方案"并非唯一形态,各语言实现可按需选择。

复杂度分析

  • 时间复杂度 O(n)O(n):每个节点最多被访问常数次;
  • 空间复杂度 O(n)O(n):递归深度与链表中的"对数"成正比,最坏为 n/2n/2 层调用栈。题目节点数上限 100 时栈开销可忽略,但从源码结构看,若该模式推广到更长的链表(如 LeetCode 25 的 k 个一组翻转),递归深度会带来真实的栈压力。

解法二:迭代

核心思路

递归方案正确但栈空间为 O(n)O(n),而每一对内部其实只是三次指针写操作,完全可以在循环里完成:

  1. 设置哨兵头节点 dummy,初始指向 head,用于固定链表头部(否则第一对交换后新头会丢失);
  2. 设置两个指针 pre 与 cur,初始 pre 指向 dummy,cur 指向 head;
  3. 循环遍历:每次判断 cur 与 cur.next 是否同时非空,若为空则剩余不足一对,退出循环;否则交换 pre 后面的两个节点,并让 pre、cur 各前进一对。

以 [1,2,3,4] 推演一轮循环(初始 pre=dummy, cur=1,t=cur.next=2):

步骤 操作 效果
1 cur.next = t.next 1 -> 3,把 1 接到 2 的后继上,且提前保存了后继
2 t.next = cur 2 -> 1,完成对内的反向
3 pre.next = t dummy -> 2,把整对挂回前缀
4 pre, cur = cur, cur.next pre=1,cur=3,前进到下一对

写序是这里的正确性关键:必须先把 cur.next 改到 t.next(此时 t.next 仍是原后继),再做后两步。若顺序颠倒(例如先执行 pre.next = t),cur 对后缀的引用会被提前切断,导致丢节点。

代码实现

仓库中 Solution2.py、Solution2.cpp、Solution2.go、Solution2.java、Solution2.ts 等均实现该迭代方案。

Python3

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(next=head)
        pre, cur = dummy, head
        while cur and cur.next:
            t = cur.next
            cur.next = t.next
            t.next = cur
            pre.next = t
            pre, cur = cur, cur.next
        return dummy.next

Java

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0, head);
        ListNode pre = dummy;
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            ListNode t = cur.next;
            cur.next = t.next;
            t.next = cur;
            pre.next = t;
            pre = cur;
            cur = cur.next;
        }
        return dummy.next;
    }
}

C++

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* dummy = new ListNode(0, head);
        ListNode* pre = dummy;
        ListNode* cur = head;
        while (cur && cur->next) {
            ListNode* t = cur->next;
            cur->next = t->next;
            t->next = cur;
            pre->next = t;
            pre = cur;
            cur = cur->next;
        }
        return dummy->next;
    }
};

Go

func swapPairs(head *ListNode) *ListNode {
	dummy := &ListNode{Next: head}
	pre, cur := dummy, head
	for cur != nil && cur.Next != nil {
		t := cur.Next
		cur.Next = t.Next
		t.Next = cur
		pre.Next = t
		pre, cur = cur, cur.Next
	}
	return dummy.Next
}

TypeScript / JavaScript 版本逻辑一致,核心循环如下:

const dummy = new ListNode(0, head);
let [pre, cur] = [dummy, head];
while (cur && cur.next) {
    const t = cur.next;
    cur.next = t.next;
    t.next = cur;
    pre.next = t;
    [pre, cur] = [cur, cur.next];
}
return dummy.next;

文档中还收录了 C# 与 PHP 的迭代版本,PHP 版将两个待交换节点命名为 $first/$second,写法等价。

复杂度分析

  • 时间复杂度 O(n)O(n):一次线性遍历;
  • 空间复杂度 O(1)O(1):只使用 dummy、pre、cur、t 四个指针,无递归栈。

两种方案对比与延伸

维度 递归 迭代
时间复杂度 O(n)O(n) O(n)O(n)
空间复杂度 O(n)O(n)(调用栈) O(1)O(1)
头部处理 无需 dummy,直接返回 p 需要 dummy 固定新头
指针写次数/每对 2 次(p.next、head.next) 3 次(cur.next、t.next、pre.next)
适用场景 代码简洁、便于推导 k 组翻转的递归形式 面试首选、长链表下无栈深度风险

从源码结构看,递归版与迭代版每对节点内部的接线逻辑是同构的:迭代版的三次写操作正是把递归版"先递归拿 t、再反转当前对"展开成了原地循环。理解这一点后,该模式可以直接推广到 25. K 个一组翻转链表 与 206. 反转链表 等同类指针重排问题:前者把"交换一对"泛化为"翻转 k 个",后者的解法一同样是 swapPairs(head.next) 式的递归归约。

参考文件

登录后查看全文
leetcode