LeetCode 24 两两交换链表中的节点(指针重连经典题)
题目描述
给定一个链表,两两交换其中相邻的节点。
例如:
text
1 -> 2 -> 3 -> 4
交换后:
text
2 -> 1 -> 4 -> 3
要求:
- 不能修改节点值;
- 必须修改节点指针。
一、核心思想
每次处理两个节点。
例如:
text
1 -> 2 -> 3 -> 4
先处理:
text
1 -> 2
交换后:
text
2 -> 1
然后继续处理:
text
3 -> 4
二、为什么需要 Dummy?
第一组交换:
text
1 -> 2
交换后:
text
2 -> 1
头节点发生变化。
所以:
python
dummy = ListNode(0, head)
统一处理。
三、交换过程
假设:
text
cur -> node1 -> node2 -> next
需要变成:
text
cur -> node2 -> node1 -> next
分三步:
第一步
python
cur.next = node2
第二步
python
node1.next = node2.next
第三步
python
node2.next = node1
完成交换。
四、完整代码
python
class Solution:
def swapPairs(self, head):
dummy = ListNode(0, head)
cur = dummy
while cur.next and cur.next.next:
node1 = cur.next
node2 = cur.next.next
cur.next = node2
node1.next = node2.next
node2.next = node1
cur = node1
return dummy.next
五、复杂度分析
时间复杂度
text
O(n)
每个节点访问一次。
空间复杂度
text
O(1)
只使用几个指针变量。
六、高频易错点
1、循环条件写错
正确:
python
while cur.next and cur.next.next:
2、指针重连顺序错误
三步顺序不能乱。
3、忘记移动 cur
正确:
python
cur = node1
因为:
text
交换后 node1 成为了当前组最后一个节点。
七、一句话总结
每次取两个节点,通过三次指针重连完成交换,再移动到下一组继续处理。
记忆口诀:
text
哨兵当头,cur在前;
取出两个,三步重连;
cur后移,继续交换。