题目地址

题解
思路1:迭代
- 思路
- 分析时间复杂度O(n)空间复杂度 O(1)
- 代码实现
var swapPairs = function (head) {
if (!head || !head.next) return head
let mark = head.next
let cur = head, nxt = null, pre = head
while (cur && cur.next) {
nxt = cur.next
pre.next = nxt
cur.next = nxt.next
nxt.next = cur
pre = cur
cur = cur.next
}
return mark
};
思路2:递归
- 分析时间复杂度O(n)空间复杂度 O(1)
- 代码实现
var swapPairs = function (head) {
if (!head || !head.next) return head
let nxt = head.next
head.next = swapPairs(nxt.next)
nxt.next = head
return nxt
};
思路的通过时间的对比

