Linked List in C: A Complete Guide with Examples
A linked list is a fundamental data structure in C programming that provides a flexible way to store and manage data. Unlike arrays, linked lists do not require a predefined size and allow dynamic memory allocation. This makes them especially useful in applications where the number of data elements is unpredictable.
1. What is a Linked List?
A linked list is a collection of nodes where each node contains two parts: data and a pointer to the next node. This structure allows efficient insertion and deletion of elements.
2. Types of Linked Lists
- Singly Linked List: Each node points to the next node.
- Doubly Linked List: Each node points to both the previous and next nodes.
- Circular Linked List: The last node points back to the first node.
3. Structure of a Singly Linked List Node
struct Node {
int data;
struct Node* next;
};
4. Basic Operations on Linked Lists
- Insertion: Add a node at the beginning, middle, or end.
- Deletion: Remove a node by position or value.
- Traversal: Navigate through the list to access or display nodes.
- Search: Find a specific node based on its value.
5. Example: Creating and Traversing a Singly Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* n) {
while (n != NULL) {
printf("%d -> ", n->data);
n = n->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*) malloc(sizeof(struct Node));
second = (struct Node*) malloc(sizeof(struct Node));
third = (struct Node*) malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printList(head);
return 0;
}
6. Advantages of Linked Lists
- Dynamic size allocation
- Efficient insertion/deletion
- Better memory utilization
7. Disadvantages of Linked Lists
- More memory usage due to pointers
- Slower access time compared to arrays
- Complexity in reverse traversal (in singly linked lists)
8. Real-World Applications
- Implementing stacks and queues
- Dynamic memory allocation systems
- Graph representations (adjacency lists)
- Symbol tables in compilers
Conclusion
Linked lists in C offer a powerful alternative to arrays, especially when dealing with dynamic data. They are essential for mastering data structures and algorithms, and play a key role in various programming scenarios. Start experimenting with linked lists to enhance your understanding of memory management and pointer manipulation in C.
Keywords: Linked List in C, C Linked List Tutorial, Singly Linked List in C, C Programming Data Structures, C Dynamic Memory