AlgoViz

Introduction to Singly LinkedList

Easy

Nodes chained by a next pointer

Problem

A singly linked list is a chain of nodes; each node stores a value and a pointer 'next' to the following node, and the last node points to null. Learn to build and traverse one.

In simple words

A treasure hunt: each node holds a value and a clue (pointer) to the next node.

The idea

A node holds a value and a pointer to the next node; the list is whatever you can reach from the head. There is no index arithmetic, so reaching position k costs k steps — but inserting or deleting once you are there costs nothing but a pointer rewrite.

The trick

  • Access is O(n), insert and delete at a known node are O(1) — the exact opposite of an array.
  • The last node points to null; losing the head loses the whole list.
  • Almost every bug is a null dereference — check `node` before `node.next`.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

1
2
3
0
1
2

Step 1 of 2. Here's the example — values = [1, 2, 3] Values: 1, 2, 3.

1/2
Optimal
timeO(n)spaceO(1)
1struct Node { val; next }2// traverse3cur = head4while cur != null:5  visit(cur.val); cur = cur.next

Input

array
[1, 2, 3]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Example

Input:
values = [1, 2, 3]
Output:
1 -> 2 -> 3 -> NULL

Finished the walkthrough? Add it to your streak.