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 [10, 20, 30, 40] builds the chain head -> 10 -> 20 -> 30 -> 40 -> nil with one node appended per step.

Basic Implementation

basic.swift
struct ListNode {
	var value: Int
	var next: Int
}

let values = [10, 20, 30, 40]
var nodes: [ListNode] = []
var head = -1
var tail = -1
for i in values.indices {
	let idx = nodes.count
	nodes.append(ListNode(value: values[i], next: -1))
	if head == -1 {
		head = idx
	} else {
		nodes[tail].next = idx
	}
	tail = idx
}
var cur = head
while cur != -1 {
	print("\(nodes[cur].value) -> ", terminator: "")
	cur = nodes[cur].next
}
print("nil")

Complexity

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

Implementation notes

  • Swift: a tiny struct ListNode { var value: Int; var next: Int } stored in a var nodes: [ListNode] arena. The integer next 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 a class-based graph with shared references.
  • The replay never shows runtime references; nodes are labelled node(<value>) and the chain view is rendered as 10 -> 20 -> ... -> nil.
  • The arena is owned by the function frame and dropped at scope exit, so the build step stays focused on wiring without an explicit free walk.
node chain Each `ListNode` carries an `Int value` and an `Int next` index into the node arena (`-1` is the end-of-list sentinel).