How to Create a Linked List in C: Syntax and Example
To create a linked list in C, define a
struct for the node containing data and a pointer to the next node. Then, dynamically allocate nodes using malloc and link them by setting the next pointers.Syntax
A linked list node in C is defined using a struct that contains two parts:
- Data: The value stored in the node (e.g., an integer).
- Next pointer: A pointer to the next node in the list.
Example syntax:
c
struct Node {
int data;
struct Node* next;
};Example
This example creates a linked list with three nodes holding values 10, 20, and 30, then prints them.
c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// Allocate 3 nodes in the heap
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
// Assign data and link nodes
head->data = 10;
head->next = second;
second->data = 20;
second->next = third;
third->data = 30;
third->next = NULL;
// Print the linked list
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
// Free allocated memory
free(third);
free(second);
free(head);
return 0;
}Output
10 20 30
Common Pitfalls
- Forgetting to allocate memory with
malloccauses undefined behavior. - Not setting the
nextpointer toNULLat the end leads to errors when traversing. - Failing to free allocated memory causes memory leaks.
- Mixing up
struct Node*andNodetypes can cause compilation errors.
c
/* Wrong: Missing malloc and next pointer */ struct Node node1; node1.data = 5; // node1.next is uninitialized /* Right: Using malloc and setting next to NULL */ struct Node* node1 = (struct Node*)malloc(sizeof(struct Node)); node1->data = 5; node1->next = NULL;
Quick Reference
- Define node with
structcontaining data andnextpointer. - Use
mallocto create nodes dynamically. - Link nodes by setting
nextpointers. - Traverse list by following
nextuntilNULL. - Always free memory with
freewhen done.
Key Takeaways
A linked list node in C is a struct with data and a pointer to the next node.
Use malloc to allocate memory for each node and link them with next pointers.
Always set the last node's next pointer to NULL to mark the list end.
Traverse the list by moving from one node to the next until NULL is reached.
Free all allocated memory to avoid memory leaks.