1. Array Node Storage & Two-Pointer Linking
Intuition
1. Traverse list and store node references in an array nodes.
2. Use two indices i = 0 and j = nodes.length - 1.
3. While i < j:
- nodes[i].next = nodes[j]
- i++
- If i == j, break.
- nodes[j].next = nodes[i]
- j--
4. Terminate with nodes[i].next = null.
When to apply: Quick solution when extra O(N) memory is acceptable.
Algorithm
- Collect all nodes into a vector/array.
- Run two pointers from ends towards center.
- Wire alternating next pointers.
- Set last center node's next to null.
#include <iostream>#include <vector> 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: void reorderList(ListNode* head) { if (!head || !head->next) return; std::vector<ListNode*> nodes; ListNode* curr = head; while (curr != nullptr) { nodes.push_back(curr); curr = curr->next; } int i = 0, j = nodes.size() - 1; while (i < j) { nodes[i]->next = nodes[j]; i++; if (i >= j) break; nodes[j]->next = nodes[i]; j--; } nodes[i]->next = nullptr; }}; int main() { ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))); Solution sol; sol.reorderList(head); ListNode* curr = head; while (curr != nullptr) { std::cout << curr->val << " "; curr = curr->next; } std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— One pass to populate the array (N steps) and one pass of two-pointer rewiring (N steps): O(N) overall. - Space complexity:
O(N)— O(N) memory to store references to all N nodes in an array.