原理
测试案例 1,2,3,4,创建虚拟头结点,然后dummyhead连2,2连1, 1连3,完成一次交换动作
注意终止循环条件设置和两个节点的临时记录
实现
力扣24.两两交换链表中的节点
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
// 测试案例 1,2,3,4
var swapPairs = function (head) {
// 创建虚拟头结点
let dummyHead = new ListNode()
dummyHead.next = head
// 临时节点,用于遍历链表
let cur = dummyHead
while (cur.next !== null && cur.next.next !== null) {
// 保存1
temp1 = cur.next
// 保存3
temp2 = cur.next.next.next
// 实现交换,dummyhead连2,2连1, 1连3,完成一次交换动作
cur.next = cur.next.next
cur.next.next = temp1
cur.next.next.next = temp2
// cur向后移动
cur = cur.next.next
}
return dummyHead.next
}
这样可能好理解点,
var swapPairs = function (head) {
let dummyHead = new ListNode()
dummyHead.next = head
let cur = dummyHead
while (cur.next !== null && cur.next.next !== null) {
let one = cur.next
let two = cur.next.next
let three = two.next
// d2
cur.next = two
// 21
two.next = one
// 13
one.next = three
cur = cur.next.next
}
return dummyHead.next
}