Linked Structures
Delete by Value
Find the node before the target value and rewire its next pointer so the target node leaves the chain.
Algorithm
The replay labels nodes by value, such as node(20), and never exposes object
identity or memory addresses. This SQL DSA implementation uses the
same small chain as the rest of the DSA track.
Basic Implementation
basic.sql
.mode list
.headers off
CREATE TABLE node(idx INTEGER PRIMARY KEY, val INTEGER, next_idx INTEGER);
INSERT INTO node(idx, val, next_idx) VALUES (1, 10, 2), (2, 20, 3), (3, 30, 4), (4, 40, NULL);
UPDATE node SET next_idx = (SELECT next_idx FROM node WHERE val = 30) WHERE idx = 2;
DELETE FROM node WHERE val = 30;
WITH RECURSIVE walk(idx, line) AS (
SELECT 1, CAST(val AS TEXT) || ' -> ' FROM node WHERE idx = 1
UNION ALL
SELECT node.idx, walk.line || CAST(node.val AS TEXT) || ' -> '
FROM walk JOIN node ON node.idx = (SELECT next_idx FROM node WHERE idx = walk.idx)
)
SELECT line || 'null' FROM walk
ORDER BY LENGTH(line) DESC LIMIT 1;
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- Keep the explicit node and pointer/reference operations; array shortcuts hide the linked-list state this lesson is meant to replay.
- The final output prints the chain in a deterministic
a -> b -> nullform for cross-language comparison.
predecessor
Deletion needs the node before the one being removed.
rewiring
The predecessor skips the target and points at the target's next node.