Odd Even Linked List

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example: Given 1->2->3->4->5->NULL, return 1->3->5->2->4->NULL.

Note: The relative order inside both the even and odd groups should remain as it was in the input. The first node is considered odd, the second node even and so on ...

Credits:Special thanks to @DjangoUnchained for adding this problem and creating all test cases.

Solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
  public ListNode oddEvenList(ListNode head) {
        if (head == null) {
            return null;
        }

        ListNode dummyHead = new ListNode(-1);
        ListNode dummy1 = new ListNode(1);
        ListNode dummy2 = new ListNode(2);
        dummyHead.next = dummy1;
        dummy1.next = dummy2;
        dummy2.next = head;

        ListNode pivot1 = dummy1;
        ListNode pivot2 = dummy2;

        int index = 1;
        ListNode runner = head;
        while (runner != null) {
            ListNode next = runner.next;

            if (index % 2 == 1) {
                // odd
                ListNode temp = pivot1.next;
                pivot1.next = runner;
                runner.next = temp;
                pivot2.next = next;
                pivot1 = pivot1.next;
            } else {
                // even
                pivot2 = pivot2.next;
            }

            runner = next;
            index ++;
        }

        runner = dummyHead;
        while (runner.next != dummy1) {
            runner = runner.next;
        }
        runner.next = runner.next.next;

        while (runner.next != dummy2) {
            runner = runner.next;
        }
        runner.next = runner.next.next;

        return dummy1.next;
    }

}

results matching ""

    No results matching ""