Java: solution with maintaining two references to even/odd tails


  • 0
    E
    public ListNode oddEvenList(ListNode head) {
       // Initialize even/odd dummy heads
       ListNode dummyEvenHead = new ListNode(0);
       ListNode dummyOddHead = new ListNode(0);
       int turn = 1;
       // Create a list of even/odd tails
       List<ListNode> tails = Arrays.asList(dummyEvenHead, dummyOddHead);
       // Run through the array adding even/odd nodes to the corresponding sublists
       for (ListNode runner = head; runner != null; runner = runner.next) {
           tails.get(turn).next = runner;
           tails.set(turn, tails.get(turn).next);
           turn ^= 1;
         }
       // Set the tails accordingly
       tails.get(0).next = null;
       tails.get(1).next = dummyEvenHead.next;
       // Return the real head 
       return dummyOddHead.next;
     }

Log in to reply
 

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