Leecode 0024. Swap Nodes in Pairs
24. Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Explanation:
Example 2:
- Input: head = []$
- Output: []
Example 3:
- Input: head = [1]
- Output: [1]
Example 4:
Input: head = [1,2,3]
Output: [2,1,3]
题目大意
给定一个链表,要求两两交换相邻节点(如 1→2→3→4 变为 2→1→4→3),且只能通过调整节点指针实现,不能修改节点内部的值。最终返回交换后链表的头节点,需处理空链表或仅含一个节点的边界情况。
解题思路
采用虚拟头节点 + 迭代的方法,通过固定的指针操作步骤实现两两交换,避免处理头节点的特殊逻辑:
- 定义虚拟头节点(
dummyHead
),使其指向原链表头节点,简化头节点交换的边界处理。 - 定义当前指针(
curr
),初始指向虚拟头节点,用于定位每次需要交换的两个节点的前驱。 - 每次交换时,需保存三个关键指针(待交换的两个节点
node1
、node2
,以及node2
的后继nextNode
),避免指针丢失。 - 按固定顺序调整指针:
curr
指向node2
→node2
指向node1
→node1
指向nextNode
。 - 更新
curr
到node1
(下一轮交换的前驱),重复步骤 3-4,直到没有可交换的节点(curr
的后继为null
或仅一个节点)。
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.