Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

143. Reorder List 🌟🌟

You are given the head of a singly linked-list. The list can be represented as:

L0 β†’ L1 β†’ … β†’ Ln - 1 β†’ Ln Reorder the list to be on the following form: L0 β†’ Ln β†’ L1 β†’ Ln - 1 β†’ L2 β†’ Ln - 2 β†’ …

You may not modify the values in the list’s nodes. Only nodes themselves may be changed.

Most intuitive (Using stack)

Code

class Solution {
public:
    void reorderList(ListNode* head)
    {
        int listLen = 0;
        stack<ListNode*> stk;

        // Count the length & push node in stack.
        ListNode* p = head;
        while (p) {
            listLen++;
            stk.push(p);
            p = p->next;
        }

        // Reorder the list.
        ListNode* curr = head;
        listLen /= 2;
        while (listLen--) {
            ListNode* stkTop = stk.top();
            stk.pop();
            ListNode* nxt = curr->next;
            curr->next = stkTop;
            stkTop->next = nxt;
            curr = nxt;
        }

        // Set last node to NULL
        curr->next = nullptr;
    }
};

Using Dequeue

Code

class Solution {
public:
    void reorderList(ListNode* head)
    {
        deque<ListNode*> dq;
        ListNode *prev = head, *curr = head->next;
        while (curr) {
            dq.push_back(curr);
            prev->next = nullptr;
            prev = curr;
            curr = curr->next;
        }
        curr = head;
        while (!dq.empty()) {
            curr->next = dq.back();
            dq.pop_back();
            curr = curr->next;
            if (!dq.empty()) {
                curr->next = dq.front();
                dq.pop_front();
                curr = curr->next;
            }
        }
    }
};