Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the nodes, only nodes itself may be changed.

Example

Input: head = [1,2,3,4] Output: [2,1,4,3]
Input: head = [] Output: []
Input: head = [1] Output: [1]

Solution

/**
 * 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}
 */
var swapPairs = function(head) {
    var headNode = new ListNode(null, head);
    var pre = headNode;
    var cur = head;
    while(cur && cur.next){
        let curTmp = cur;
        let nextTmp = cur.next;
        curTmp.next = nextTmp.next;
        pre.next = nextTmp;
        nextTmp.next = curTmp;
        pre = curTmp;
        cur = curTmp.next;
    }
    return headNode.next;
};

Idea

To swap pairs of nodes in the given linked list through iteration, simply traverse the entire list. First, define an empty head node, then define the previous node and the current node to be processed. While the current node and its next node exist, cache the current node and the next node. Then, set curNode.next to nextNode.next, making the next node the next node of the current node. Next, set preNode.next to nextNode, and set nextNode.next to curNode. Finally, set preNode to curNode, and curNode to curNode.next. At this point, curNode has actually been swapped with the latter node of the two. After the loop is completed, return the next of the head node.

Daily Question

https://github.com/WindrunnerMax/EveryDay

Reference

https://leetcode-cn.com/problems/swap-nodes-in-pairs/