Java simple 1 ms solution with explaination


  • 4
    C

    The idea is simple. Have a pointer for the beginning of odd and a pointer for beginning of even,
    then we have a odd pointer that points the current odd node and use it to connect to its oddPointer.next.next, same goes for connecting even. When even pointer is null we know it's at the end of the list. Then we just merge two list and return odd head.

       public ListNode oddEvenList(ListNode head) {
        if(head == null)
            return null;
        if(head.next == null || head.next.next == null) // if there are only 1 or 2 nodes then just return head
            return head;
    
        ListNode oddHead = head;
        ListNode evenHead = head.next;
        ListNode oddP = oddHead, evenP = evenHead;
    
        while(evenP != null && evenP.next != null){
            oddP.next = oddP.next.next;
            evenP.next = evenP.next.next;
            oddP = oddP.next;
            evenP = evenP.next;
        }
        oddP.next = evenHead;  //merge odd and even 
        return oddHead;
    }

Log in to reply
 

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