Construct a singly linked list by allocating one node per value and chaining next references. Establishes the node + head + tail model used by every later linked-list lesson.

Algorithm

Canonical input c(10, 20, 30, 40) builds the chain head -> 10 -> 20 -> 30 -> 40 -> null with one node appended per step.

Basic Implementation

basic.R
values <- c(10, 20, 30, 40)
nodes <- list()
head <- -1
tail <- -1
i <- 1
while (i <= length(values)) {
	idx <- length(nodes) + 1
	nodes[[idx]] <- list(value = values[i], next_idx = -1)
	if (head == -1) {
		head <- idx
	} else {
		nodes[[tail]]$next_idx <- idx
	}
	tail <- idx
	i <- i + 1
}
cur <- head
while (cur != -1) {
	cat(nodes[[cur]]$value, " -> ", sep = "")
	cur <- nodes[[cur]]$next_idx
}
cat("null\n", sep = "")

Complexity

  • Time: O(n) with a tail pointer
  • Space: O(n) for the chain

Implementation notes

  • R: a tiny named list(value = ..., next_idx = ...) per node stored in a plain integer-keyed nodes list arena. The integer next_idx field with -1 as the sentinel is the explicit "end-of-list" marker and lets the head / tail pointers update the chain without leaning on environments, reference classes, or a recursive environment graph.
  • The replay never shows runtime references (R lists print with their contents inline, but the lesson renders nodes as node(<value>) and the chain view as 10 -> 20 -> ... -> null).
  • The arena is collected by R's GC at script exit, so the build step stays focused on wiring without an explicit free walk.
node chain Each node carries a `value` and a `next_idx` index into the node arena (`-1` is the end-of-list sentinel).