Java instructive


  • 1
    B

    I got this from looking at other solutions. Accepted. Just keep odd and even links and skip by 2 through the list. Then set last odd node to head of even node (2nd node in original list)

    public ListNode oddEvenList(ListNode head) {

        if (head == null)
            return null;
    
        ListNode odd = head;
        ListNode oddTail = head;
        ListNode even = head.next;
        ListNode evenHead = even;
       
        while(odd != null){
            if (odd.next != null)
                odd.next = odd.next.next;
            if (even != null && even.next != null)
                even.next = even.next.next;
            
            oddTail = odd;
           
            if (odd != null)
                odd = odd.next;
            if (even != null)
                even = even.next;
        }
        
        oddTail.next = evenHead;
        return head;
    }

  • 0
    Z
    This post is deleted!

Log in to reply
 

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