1. Brute Force — Shift All Values to Left
Intuition
Iterate from the target node to the end of the list. At each step, copy the next node's value to the current node. Finally, delete the tail node.
Algorithm
- Step 1: Set pointer
curr = node. - Step 2: While
curr.next.next != null, setcurr.val = curr.next.valand advancecurr = curr.next. - Step 3: At the second-to-last node, set
curr.val = curr.next.valand disconnectcurr.next = null.
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}}; class Solution {public: void deleteNode(ListNode* node) { ListNode* curr = node; while (curr->next->next != nullptr) { curr->val = curr->next->val; curr = curr->next; } curr->val = curr->next->val; delete curr->next; curr->next = nullptr; }}; int main() { ListNode* head = new ListNode(4); ListNode* node5 = new ListNode(5); ListNode* node1 = new ListNode(1); ListNode* node9 = new ListNode(9); head->next = node5; node5->next = node1; node1->next = node9; Solution sol; sol.deleteNode(node5); cout << "Brute Force Result: "; ListNode* curr = head; while (curr) { cout << curr->val << (curr->next ? " -> " : ""); curr = curr->next; } cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Traverses and writes values for all K remaining nodes in the list. - Space complexity:
O(1)— Modifies node values in place without allocating extra memory.
Why Brute Force Doesn't Scale:
Shifting all subsequent values takes O(K) time where K is the distance to the tail.
For a list of 1,000,000 nodes, shifting values takes ~3ms. O(1) value copying takes 0.0001ms.