328. Odd Even Linked List – Solution [Brute-Force to Best]

Here’s the question link on Leetcode 328. Odd Even Linked List:

https://leetcode.com/problems/odd-even-linked-list/description

Brute Force – Using Two Arrays

We can traverse the linked list and store the odd-positioned and even-positioned node values in two separate arrays.

Then, update the linked list by placing all odd-positioned values first, followed by even-positioned values.

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(head == NULL) return head;

        vector<int> odd, even;

        ListNode* temp = head;
        int pos = 1;

        while(temp != NULL) {
            if(pos % 2 == 1)
                odd.push_back(temp->val);
            else
                even.push_back(temp->val);

            temp = temp->next;
            pos++;
        }

        temp = head;

        for(int x : odd) {
            temp->val = x;
            temp = temp->next;
        }

        for(int x : even) {
            temp->val = x;
            temp = temp->next;
        }

        return head;
    }
};
328. Odd Even Linked List

Optimal – In-place Pointer Manipulation

We don’t actually need extra arrays. We can rearrange the links between nodes directly.

We’ll maintain two pointers:

  • odd – Points to the last node in the odd-positioned group.
  • even – Points to the last node in the even-positioned group.

We’ll also save the original head of the even group because we’ll need to attach it after the odd group at the end.

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return head;

        ListNode* odd = head;
        ListNode* even = head->next;
        ListNode* evenHead = even;

        while(even != NULL && even->next != NULL) {
            odd->next = even->next;
            odd = odd->next;

            even->next = odd->next;
            even = even->next;
        }

        odd->next = evenHead;

        return head;
    }
};
328. Odd Even Linked List

Leave a Reply