LeetCode 24. 两两交换链表中的节点

题目描述

24. 两两交换链表中的节点

image-20230306193333611

思路分析

递归和迭代

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func swapPairs(head *ListNode) *ListNode {
	dummy := &ListNode{Next: head}
	pre := dummy

	for pre.Next != nil && pre.Next.Next != nil {
		first := pre.Next
		second := pre.Next.Next

		first.Next = second.Next
		second.Next = first
		pre.Next = second

		pre = first
	}

	return dummy.Next
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func swapPairs(head *ListNode) *ListNode {
	dummy := &ListNode{Next: head}
	pre := dummy
	cur := head

	for cur != nil && cur.Next != nil {
		first := cur
		second := cur.Next

		first.Next = second.Next
		second.Next = first
		pre.Next = second

		pre = first
		cur = first.Next
	}

	return dummy.Next
}
  • 时间复杂度:O (n),其中 n 是链表的长度。
  • 空间复杂度:O (1),我们只使用了常数的额外空间。
1
2
3
4
5
6
7
8
9
10
11
12
13
func swapPairs(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}

	first := head
	second := head.Next

	first.Next = swapPairs(second.Next)
	second.Next = first

	return second
}
  • 时间复杂度:O (n),其中 n 是链表的长度。
  • 空间复杂度:O (n),其中 n 是链表的长度。

➡️ 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/54774613
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!