24.两两交换链表中的节点


function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function (head) {
    if (!head || head.next === null) {
        return head
    }
    let prehead = new ListNode()
    let pre = prehead
    let cur = head
    while (cur && cur.next) {
        // 注意有三条链
        let node1 = cur
        let node2 = cur.next

        pre.next = node2
        node1.next = node2.next
        node2.next = node1

        pre = node1
        cur = node1.next
    }
    return prehead.next
};

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
// 这样交换更好理解
var swapPairs = function (head) {
    let prehead = new ListNode()
    prehead.next = head
    let cur = prehead
    while (cur.next && cur.next.next) {
        // 交换两个节点
        let node1 = cur.next
        let node2 = cur.next.next

        cur.next = node2
        node1.next = node2.next
        node2.next = node1

        cur = node1
    }
    return prehead.next
}

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
// 试试递归
var swapPairs = function (head) {
    if(!head || !head.next) {
        return head
    }
    // 需要交换的两个节点
    let node1 = head
    let node2 = head.next

    let next = node2.next
    node2.next = node1
    node1.next = swapPairs(next)

    return node2
}