Singly Linked List
Build, traverse, and destroy a linked list.
What is Singly Linked List?
Each node stores a value and a link to the next node, allowing insertion without shifting contiguous elements.
Important points
- State the invariants before implementing operations.
- Handle empty, full, and allocation-failure cases.
- Measure time complexity and memory ownership together.
See how it works
Add nodes at the front or the back and click a node to delete it. Press Play to follow the next pointers from head to NULL.
C and C++ code examples
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
} Node;
int main(void) {
Node *head = NULL;
for (int value = 3; value >= 1; --value) {
Node *node = malloc(sizeof *node);
if (!node) return 1;
*node = (Node){value, head};
head = node;
}
while (head) {
Node *next = head->next;
printf("%d ", head->value);
free(head);
head = next;
}
puts("");
return 0;
}
1 2 3
#include <iostream>
#include <memory>
struct Node {
int value;
std::unique_ptr<Node> next;
};
int main() {
std::unique_ptr<Node> head;
for (int value = 3; value >= 1; --value) {
head = std::make_unique<Node>(Node{value, std::move(head)});
}
for (Node *node = head.get(); node; node = node->next.get()) {
std::cout << node->value << ' ';
}
std::cout << '\n';
}
1 2 3
C and C++ comparison
The C version owns nodes through malloc and must free every node. The C++ version uses unique_ptr so destroying the head recursively releases the chain.
Structures and operations are usually separate and allocation is explicit.
Classes and containers can preserve invariants and manage resources automatically.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add empty and capacity-boundary tests.
- Implement cleanup and verify no leaks remain.
- Compare operation complexity with a standard container.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges