1. Title Description

  • Given a linked list, swap adjacent nodes in pairs and return the head of the swapped list. You must do this without changing the values inside the nodes (that is, swapping nodes only).

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

Analysis of the

Create a virtual head node that points to the head in the list

We define a temp pointer that points to the virtual head node and we define a pre pointer that points to the node next to the temp pointer and we define a cur pointer that points to the node next to the node that the Pre pointer points to

Make the node that Pre points to point to the next node that cur points to point to the node that Pre points to

So temp goes to cur and pre goes to the next node that’s cur and pre goes to the next node that’s cur

Continue pointing to the above operations

Repeat until pre or cur points to null

Tidy it up

Two, code implementation

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function(head) {
    let ret = new ListNode(-1,head)
    let temp = ret
    while(temp.next&&temp.next.next){
        let pre = temp.next
        let cur = temp.next.next
        pre.next = cur.next
        cur.next = pre
        temp.next = cur
        temp = pre
    }
    return ret.next
};
Copy the code