Walk from the head pointer to null, visiting each node exactly once without random indexing.

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, NULL);
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 -> null form for cross-language comparison.
cursor A cursor reference names the node currently being visited.
null stop Traversal ends when the cursor reaches the null marker.