LeetCode 24. 两两交换链表中的节点
题目描述
思路分析
递归和迭代
参考代码
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 是链表的长度。
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用