25题是每k个reverse,这一题是每2个reverse,这里就可以直接拿25题的代码用了
使用reverse方法
var swapPairs = function (head) {
if (!head) return head
let left = head, right = head
for (let i = 0; i < 2; ++i) {
// 不足两个就是到尾部了,直接衔接即可
if (!right) return head
right = right.next
}
// 反转后得到的新链表
let list = reverse(left, right)
// 将新链表与后面的衔接
left.next = swapPairs(right)
return list
};
// 区间内进行reverse
var reverse = function (left, right) {
let pre = null, current = left
while (current !== right) {
let currentNext = current.next
current.next = pre
pre = current
current = currentNext
}
return pre
}
递归
递归的思路就比较简单一些了
var swapPairs = function (head) {
if (!head || !head.next) return head
let nextHead = head.next
head.next = swapPairs(nextHead.next)
nextHead.next = head
return nextHead
};
迭代
这里需要设置头节点dummy,方便后续返回链表头
var swapPairs = function (head) {
if (!head) return head
let dummy = new ListNode(-1)
dummy.next = head
let current = dummy
while (current.next && current.next.next) {
let first = current.next
let second = current.next.next
current.next = second
first.next = second.next
second.next = first
// 挪动current节点
current = first
}
return dummy.next
};