Easy to understand JavaScript Solution


  • 0
    R

    Just like the "fake-head, iterative" algorithm in many other posts, with 2 differences, which I think make it easier to understand:

    1. We don't really need a ListNode as the "fake-head", we can just use null;
    2. Instead of cur.next and cur.next.next, I think p1, p2 is better;

    [prev] -> [p1] -> [p2] -> always swap p1 with p2

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var swapPairs = function(head) {
      if (head === null) return null;
      
      var prev = null,
        p1 = head,
        p2 = p1.next;
      
      while (p2) {
        if (prev === null) {
          head = p2;
        } else {
          prev.next = p2;
        }
        p1.next = p2.next;
        p2.next = p1;
        prev = p1;
        
        p1 = p1.next;
        p2 = p1 === null ? null : p1.next;
      }
      
      return head;
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.