Java Solution 1ms, O(N) time, O(1) space


  • 0
    J
    public static ListNode oddEvenList(ListNode head)
    {
        if (head == null || head.next == null || head.next.next == null)
        {
            return head;
        } 
        else
        {
            ListNode h2, p, c;
            int counter = 0;
    
            h2 = head.next;
            c = head;
            boolean headSet = false;
    
            while (c != null)
            {
                p = c;
                counter++;
                if (c.next == null)
                {
                    c = c.next;
                    if (counter % 2 == 1)
                    {
                        p.next = h2;
                        headSet = true;
                    }
                    else p.next = null;
                } 
               else
                {   
                    c = c.next;
                    if (p.next.next ==null && counter%2 ==1)
                        p.next = h2;
                    else
                        p.next = p.next.next;
                }
            }
        }
        return head;
    }

Log in to reply
 

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