Java simple 1 ms solution with explaination

  • 4

    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, 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( == null || == null) // if there are only 1 or 2 nodes then just return head
            return head;
        ListNode oddHead = head;
        ListNode evenHead =;
        ListNode oddP = oddHead, evenP = evenHead;
        while(evenP != null && != null){
            oddP =;
            evenP =;
        } = 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.