The topic of dry

Given a linked list, swap adjacent nodes in pairs and return the swapped list.

You can’t just change the values inside a node, you need to actually swap nodes.

Example 1:

Input: head = [1,2,3,4] output: [2,1,4,3]Copy the code

Solution: Iteration

We use the iterative method to set three Pointers, among which we need to set a front pointer, three Pointers to operate, and finally return the next node of the front pointer we defined, which is our current head node. Because we use the head node for movement in the following code.

Execution time: 72 ms, beating 97.05% of all JavaScript commits

Memory consumption: 37.8 MB, beating 85.16% of all JavaScript commits

/** * 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) {
    let dummy = new ListNode(1);
    dummy.next = head;
    let prev=dummy
    while(head! =null&&head.next! =null) {
        let current=head;
        let next=head.next;
        // Switch places
        current.next = next.next;
        next.next = current;
        // After the swap is complete, the last pointer position points to the current first node
        prev.next = next
        / / shift
        prev = current;
        head=current.next
    }
    return dummy.next
};
Copy the code