JavaScript Solution


  • 1
    L
    function oddEvenList(head) {
      if (!head) return head;
    
      var odd = head;
      var even = head.next;
      while (odd.next && odd.next.next) {
        var tmp = odd.next;
        odd.next = odd.next.next;
        odd = odd.next;
        tmp.next = odd.next;
      }
      odd.next = even;
      return head;
    }

  • 1
    T

    It seems this solution does not work for even length arrays such as [1,2,3,4,5,6,7,8]. That can be corrected by adding a conditional check:

     var oddEvenList = function(head) {
        if (!head) return head;
        
        var odd = head,
            even = head.next;
        
        while (odd && odd.next ) {
            var tmp = odd.next;  
            odd.next = odd.next.next;  
            if ( odd.next ) {
                odd = odd.next;
                tmp.next = odd.next;     
            }
        }
            
        odd.next = even;
        
        return head;
    };

  • 0
    L

    The original code does work with even length array.
    You need extra checking because you modified the while loop from
    while (odd.next && odd.next.next)
    to
    while (odd && odd.next )


  • 1
    T

    Ah yeah that's right, that's embarrassing but you're right on that. Thanks for the clarification!


  • 1
    E

    This isn't O(1) space complexity, though.


  • 0
    L

    why? some compiler issue?


Log in to reply
 

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