Simple java solution 2 pointers


  • 0
    C
    public ListNode oddEvenList(ListNode head) {
            if(head == null || head.next == null || head.next.next == null) return head;
            ListNode oddTail = head; //tracks the tail of all odd nodes
            ListNode seekOdd = head; //seeks next odd node
            while(seekOdd.next!=null && seekOdd.next.next!=null){
                ListNode bigEven = seekOdd.next; //biggest even node between oddTail and seekOdd
                seekOdd = seekOdd.next.next; 
                ListNode smallEven = oddTail.next; //smallest even node between oddTail and seekOdd
                oddTail.next = seekOdd;
                bigEven.next = seekOdd.next;
                seekOdd.next = smallEven;
                oddTail = seekOdd;
                seekOdd = bigEven;
            }
            return head;
        }
    

Log in to reply
 

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