Insert a new first node by pointing it at the old head and then moving the head pointer.

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 (2, 20, 3), (3, 30, NULL);
INSERT INTO node(idx, val, next_idx) VALUES (1, 10, 2);
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(1)
  • 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 -> null form for cross-language comparison.
old head The previous first node becomes the second node.
constant-time insert Only the new node and head pointer change.