0%

LeetCode-24

题目

结果

代码

递归

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode tmp = head.next;
head.next = swapPairs(head.next.next);
tmp.next = head;
return tmp;
}
}

迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
Queue<ListNode> queue = new LinkedList<>();
ListNode p = head;
while (p.next != null) {
queue.add(p.next);
queue.add(p);
if (p.next.next == null) {
break;
} else if (p.next.next.next == null) {
queue.add(p.next.next);
break;
} else {
p = p.next.next;
}
}
ListNode ans = queue.poll();
p = ans;
while (!queue.isEmpty()) {
p.next = queue.poll();
p = p.next;
if (queue.size() == 0) {
p.next = null;
}
}
return ans;
}
}

复杂度

时间复杂度:O(n)

空间复杂度:O(n)