1. Array Extraction and Rebuild
Intuition
1. Iterate through the input list, appending any node.val != val into an array/list.
2. Iterate through the collected array and allocate new ListNode instances linked sequentially.
3. Return the head of the new list.
When to apply: Quick conceptual prototype when linked list pointer manipulations are prohibited or tricky.
Algorithm
- Traverse linked list and append values
!= valto a dynamic arraynums. - If
numsis empty, return null. - Create a new list from elements in
numsand return its head.
#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: ListNode* removeElements(ListNode* head, int val) { std::vector<int> kept; ListNode* curr = head; while (curr != nullptr) { if (curr->val != val) { kept.push_back(curr->val); } curr = curr->next; } if (kept.empty()) return nullptr; ListNode* newHead = new ListNode(kept[0]); ListNode* tail = newHead; for (size_t i = 1; i < kept.size(); ++i) { tail->next = new ListNode(kept[i]); tail = tail->next; } return newHead; }}; int main() { ListNode* head = new ListNode(1, new ListNode(2, new ListNode(6, new ListNode(3, new ListNode(4, new ListNode(5, new ListNode(6))))))); Solution sol; ListNode* res = sol.removeElements(head, 6); while (res != nullptr) { std::cout << res->val << " "; res = res->next; } std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— We perform one pass to collect values (N steps) and a second pass to construct N new nodes. - Space complexity:
O(N)— O(N) extra memory to hold the filtered values in an array and allocate duplicate nodes.