Linked Lists in C
Until now, you have mostly used arrays to store data.
Arrays work well, but they have a big limitation — their size is fixed.
To overcome this problem, C provides a powerful dynamic data structure called a Linked List.
What Is a Linked List?
A linked list is a collection of nodes where each node:
- Stores data
- Stores the address of the next node
Nodes are connected using pointers.
Why Not Just Use Arrays?
Arrays have these limitations:
- Fixed size
- Insertion is expensive
- Deletion is difficult
Linked lists solve these problems by using dynamic memory allocation.
Structure of a Linked List Node
Each node contains:
- Data part
- Pointer to the next node
struct Node {
int data;
struct Node *next;
};
Creating a Node
Nodes are created dynamically using malloc().
struct Node *newNode;
newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = 10;
newNode->next = NULL;
Linking Nodes Together
Let’s create two nodes and connect them.
struct Node *head, *second;
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
head->data = 5;
head->next = second;
second->data = 15;
second->next = NULL;
Here, head points to the first node.
Traversing a Linked List
Traversal means visiting each node one by one.
struct Node *temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
Real-World Analogy
Think of a linked list like a treasure hunt:
- Each clue contains data
- Each clue points to the next clue
You must follow the chain to reach the end.
Advantages of Linked Lists
- Dynamic size
- Efficient insertion and deletion
- No memory wastage
Mini Practice
- Create a linked list with 3 nodes
- Store integer values
- Traverse and print the list
Quick Quiz
Q1. What is a linked list?
A dynamic data structure made of connected nodes.
Q2. What does each node contain?
Data and address of the next node.
Q3. Which function allocates memory dynamically?
malloc()
Q4. Why are linked lists better than arrays?
They allow dynamic size and easy insertion/deletion.
Q5. What does the last node point to?
NULL