Featured image of post LeetCode 75 - 328. Odd Even Linked List

LeetCode 75 - 328. Odd Even Linked List

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:

img

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

Example 2:

img

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

Constraints:

  • The number of nodes in the linked list is in the range [0, 104].
  • -106 <= Node.val <= 106

Solutions

Solution 1

By traversing the linked list, construct two separate lists for odd and even nodes, and then merge the two lists.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        ListNode* odd = new ListNode(-1);
        ListNode* node = odd;
        ListNode* even = new ListNode(-1);
        ListNode* even_head = even;

        int i{1};
        while (head) {
            ListNode* n = new ListNode(head->val);
            if (i % 2 == 0) {
                even->next = n;
                even = even->next;
            } else {
                odd->next = n;
                odd = odd->next;
            }
            head = head->next;
            i++;
        }
        odd->next = even_head->next;
        return node->next;
    }
};

Solution 2

Maintain two pointers, odd and even, which point to the odd and even nodes, respectively. Initially, odd = head and even = head->next. By iterating, separate the odd and even nodes into two different linked lists. In each step, first update the odd node and then update the even node.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if (head == nullptr)
            return nullptr;
            
        ListNode* odd = head;
        ListNode* even = head->next;
        ListNode* even_head = even;

        while (even && even->next) {
            odd->next = even->next;
            odd = odd->next;
            even->next = odd->next;
            even = even->next;
        }
        odd->next = even_head;
        return head;
    }
};