Linked Structures
Build a Singly Linked List
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.cs
using System;
using System.Collections.Generic;
class ListNode {
public int Value;
public int Next;
}
class Program {
static void Main() {
int[] values = new int[] { 10, 20, 30, 40 };
List<ListNode> nodes = new List<ListNode>();
int head = -1;
int tail = -1;
for (int i = 0; i < values.Length; i++) {
int idx = nodes.Count;
nodes.Add(new ListNode { Value = values[i], Next = -1 });
if (head == -1) {
head = idx;
} else {
nodes[tail].Next = idx;
}
tail = idx;
}
int cur = head;
while (cur != -1) {
Console.Write(nodes[cur].Value + " -> ");
cur = nodes[cur].Next;
}
Console.WriteLine("nil");
}
}
Complexity
- Time: O(n) with a tail pointer
- Space: O(n) for the chain
Implementation notes
- C#: a small
class ListNode { public int Value; public int Next; }stored in aList<ListNode>arena. The integerNextfield with-1as the sentinel is the explicit "end-of-list" marker and lets thehead/tailpointers update the chain without leaning on the standardLinkedList<T>. - The replay never shows runtime references; nodes are labelled
node(<value>)and the chain view is rendered as10 -> 20 -> ... -> nil. - The arena is collected by the GC 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).