A linked list in C is a chain of heap-allocated nodes, where each node holds a value and a pointer to the next node, and the last pointer is NULL. To build one, define a self-referencing struct, allocate each node with malloc, and keep a pointer to the first node.
This article builds a singly linked list of int values one operation at a time, then gives the complete program. It assumes you know basic pointers; if not, read pointers in C first.
Step 1: Define the node
typedef struct Node {
int value;
struct Node *next;
} Node;
A struct cannot contain a member of its own type, because the type is incomplete until the closing brace. A pointer to its own type is allowed, and the C reference notes that this is commonly used to implement nodes in linked lists and trees. That is why next is declared as struct Node *: inside the definition the Node typedef name does not exist yet. For more on declaring and initializing structs, see struct in C.
The list itself is just a Node *head. An empty list is head == NULL. There is no separate list object in this version.
Step 2: Create a node
static Node *node_create(int value)
{
Node *node = malloc(sizeof *node);
if (node == NULL) {
return NULL;
}
node->value = value;
node->next = NULL;
return node;
}
malloc returns a null pointer on failure, so the check is required. sizeof *node keeps the size correct if you later change the struct. The returned pointer is suitably aligned for any object type with fundamental alignment, so no cast or extra alignment work is needed. Every node you allocate must be released with free later; malloc in C covers the failure and leak rules in detail.
Step 3: Insert at the head
bool list_push_front(Node **head, int value)
{
Node *node = node_create(value);
if (node == NULL) {
return false;
}
node->next = *head;
*head = node;
return true;
}
The function takes Node **head, a pointer to the caller's head pointer, because it has to change where the head points. Passing Node *head by value would only change a local copy. Inserting at the head takes constant time: the new node points at the old first node, then becomes the first node. If allocation fails, the list is left untouched and the function returns false.
Step 4: Insert at the tail
bool list_push_back(Node **head, int value)
{
Node *node = node_create(value);
if (node == NULL) {
return false;
}
Node **link = head;
while (*link != NULL) {
link = &(*link)->next;
}
*link = node;
return true;
}
Here link points at whichever pointer currently holds NULL at the end: first the head pointer itself, then each node's next field. When the loop stops, assigning through link attaches the new node. The same code handles an empty list and a non-empty one, with no special case. The cost is a walk over every node, so appending n items one by one is quadratic. If you append often, keep a separate tail pointer in a small list struct.
Step 5: Search for a value
Node *list_find(const Node *head, int value)
{
for (Node *node = (Node *)head; node != NULL; node = node->next) {
if (node->value == value) {
return node;
}
}
return NULL;
}
The loop follows next until it finds a match or reaches NULL. Search is linear: finding the 1,000th item means following 999 links. There is no way to jump to the middle, which is the main trade-off against an array.
Step 6: Delete a node
bool list_remove(Node **head, int value)
{
Node **link = head;
while (*link != NULL) {
if ((*link)->value == value) {
Node *doomed = *link;
*link = doomed->next;
free(doomed);
return true;
}
link = &(*link)->next;
}
return false;
}
The pointer-to-pointer trick pays off again. When the match is found, *link is whichever pointer refers to it, either the head or the previous node's next. Overwriting it with doomed->next unlinks the node, and then free(doomed) releases it. Unlink first and free second: after free, reading doomed->next would be undefined behavior. The function removes only the first match and returns false if nothing matched.
Step 7: Reverse the list
void list_reverse(Node **head)
{
Node *previous = NULL;
Node *current = *head;
while (current != NULL) {
Node *following = current->next;
current->next = previous;
previous = current;
current = following;
}
*head = previous;
}
Reversal rewires the existing nodes in place, with no allocation. For each node, save the next one, point the current node backwards, then step forward. When current reaches NULL, previous is the old last node, which becomes the new head. It runs in one pass.
Step 8: Free the whole list
void list_free(Node **head)
{
Node *node = *head;
while (node != NULL) {
Node *following = node->next;
free(node);
node = following;
}
*head = NULL;
}
Save next before calling free on a node, for the same reason as in the delete function. Setting *head to NULL at the end leaves the caller with a valid empty list instead of a dangling pointer. Freeing a null pointer does nothing, but freeing the same node twice is undefined behavior.
The complete program
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
} Node;
static Node *node_create(int value)
{
Node *node = malloc(sizeof *node);
if (node == NULL) {
return NULL;
}
node->value = value;
node->next = NULL;
return node;
}
bool list_push_front(Node **head, int value)
{
Node *node = node_create(value);
if (node == NULL) {
return false;
}
node->next = *head;
*head = node;
return true;
}
bool list_push_back(Node **head, int value)
{
Node *node = node_create(value);
if (node == NULL) {
return false;
}
Node **link = head;
while (*link != NULL) {
link = &(*link)->next;
}
*link = node;
return true;
}
bool list_remove(Node **head, int value)
{
Node **link = head;
while (*link != NULL) {
if ((*link)->value == value) {
Node *doomed = *link;
*link = doomed->next;
free(doomed);
return true;
}
link = &(*link)->next;
}
return false;
}
void list_reverse(Node **head)
{
Node *previous = NULL;
Node *current = *head;
while (current != NULL) {
Node *following = current->next;
current->next = previous;
previous = current;
current = following;
}
*head = previous;
}
void list_free(Node **head)
{
Node *node = *head;
while (node != NULL) {
Node *following = node->next;
free(node);
node = following;
}
*head = NULL;
}
static void list_print(const Node *head)
{
for (const Node *node = head; node != NULL; node = node->next) {
printf("%d -> ", node->value);
}
printf("NULL\n");
}
int main(void)
{
Node *head = NULL;
list_push_back(&head, 10);
list_push_back(&head, 20);
list_push_front(&head, 5);
list_print(head);
list_remove(&head, 10);
list_print(head);
list_reverse(&head);
list_print(head);
list_free(&head);
return 0;
}
Expected output, worked out by hand from the code (example output, not a captured run):
5 -> 10 -> 20 -> NULL
5 -> 20 -> NULL
20 -> 5 -> NULL
Compile it with any C99 or later compiler, for example gcc -Wall -Wextra -o list list.c. To check for leaks and invalid frees, build with -fsanitize=address where your compiler supports it.
Common mistakes with linked lists in C
- Losing the rest of the list. Overwriting
heador anextpointer before saving the old value orphans every node behind it. Those nodes can no longer be freed, which is a memory leak. - Using a node after freeing it. Reading
node->nextafterfree(node)is undefined behavior, even if it appears to work. - Passing the head by value. A function that takes
Node *headcan modify nodes but cannot change which node is first. UseNode **head, or return the new head and make the caller assign it. - Forgetting the empty list. Every function above treats
*head == NULLas a valid list. Test that case first. - Not checking
malloc. A null return means failure, and writing through it is undefined behavior.
Singly, doubly, and circular lists
The list above is singly linked: you can only move forward. A doubly linked list adds a prev pointer to each node, so you can walk both ways and unlink a node you already hold without searching for its predecessor, at the cost of one more pointer per node and more pointer updates on every insert. A circular list points the last node back at the first, which suits round-robin traversal. The step-by-step approach is the same: define the node, allocate with malloc, rewire pointers carefully, and free every node exactly once.
If it crashes
A segmentation fault in a list function usually means a NULL or freed pointer was dereferenced. Print the list after each operation, as main does above, to see where it first looks wrong. Compiling with -fsanitize=address or running under Valgrind reports use-after-free and leaks with the line that caused them.
Frequently asked questions
- What is a linked list in C?
- A linked list in C is a chain of separately allocated nodes. Each node stores a value and a pointer to the next node, and the last node's pointer is NULL. You keep a pointer to the first node (the head) and follow the next pointers to reach the rest.
- Why can a struct contain a pointer to itself but not itself?
- A struct type is incomplete until the end of its definition, and members of incomplete type are not allowed, so a struct cannot contain a member of its own type. A pointer to its own type is allowed, and that is how list nodes are written.
- When should I use an array instead of a linked list?
- Use an array when you need fast access by index or want contiguous memory. A linked list gives cheap insertion and removal at a node you already hold, but reaching the n-th element means walking n links.
- Do I need to check the return value of malloc for every node?
- Yes. malloc returns a null pointer on failure, and dereferencing it is undefined behavior. In a list, a failed allocation should leave the existing list unchanged and report the failure to the caller.