Description

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

The first node is considered odd, and the second node is even, and so on.

Note that the relative order inside both the even and odd groups should remain as it was in the input.

You must solve the problem in O(1) extra space complexity and O(n) time complexity.

Example 1:

1Input: head = [1,2,3,4,5]
2Output: [1,3,5,2,4]
3Explanation:
41 --> 2 --> 3 --> 4 --> 5
5odd indices: 1 --> 3 --> 5
6even indices: 2 --> 4
7Output should be odd then even that is: 1 --> 3 --> 4 --> 2 --> 4

Example 2:

1Input: head = [2,1,3,5,6,4,7]
2Output: [2,3,6,7,1,5,4]

Constraints:

  • The number of nodes in the linked list is in the range [0, 10^4].
  • -10^6 <= Node.val <= 10^6

Solution

In this problem we have to iterate through the list and in each iteration we skip one node for one head and for another (evenHead), we add that node. Finally we add evenHead to the end of the odd.

 1class Solution {
 2    public ListNode oddEvenList(ListNode head) {
 3        if (head == null) {
 4            return null;
 5        }
 6        ListNode odd = head, even = head.next;
 7        ListNode evenHead = even; // keep evenHead to track all even indices
 8        while (even != null && even.next != null) {
 9            odd.next = even.next; // move odd to next odd
10            odd = odd.next;
11            even.next = odd.next; // move even to next even
12            even = even.next;
13        }
14        odd.next = evenHead; // connect odd list to even list
15        return head;
16    }
17}
  • Time Complexity: O(n)
  • Space Complexity: O(1)