Super simple JavaScript solution


  • 0
    D
    
    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var oddEvenList = function(head) {
        
        if(!head || !head.next || !head.next.next){
            return head;
        }
        
        let oddHead = head;
        let oddTail = head;
        let evenHead = head.next;
        let evenTail = head.next;
        
        while(oddTail && oddTail.next && oddTail.next.next && evenTail && evenTail.next && evenTail.next.next){
            let prevOdd = oddTail;        
            let prevEven = evenTail;
    
            oddTail = oddTail.next.next;
            evenTail = evenTail.next.next;
    
            prevOdd.next = oddTail;
            prevEven.next = evenTail;
        }
        
        while(oddTail && oddTail.next && oddTail.next.next){
            let prevOdd = oddTail; 
            oddTail = oddTail.next.next;
            prevOdd.next = oddTail;
        }
        
        while(evenTail && evenTail.next && evenTail.next.next){
            let prevEven = evenTail; 
            evenTail = evenTail.next.next;
            prevEven.next = evenTail;
        }
        
        evenTail.next = null;
        oddTail.next = evenHead;
        
        return oddHead;
        
        
    };
    
    
    

Log in to reply
 

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