A linked list is a linear data structure composed of nodes
A linked list is a linear data structure composed of nodes. Each node represents a single piece of data, similar to an element in an array. However, unlike arrays—where elements are stored contiguously in memory—nodes in a linked list are scattered across memory and connected through pointers.
To traverse a list where nodes are not stored sequentially, we need to keep track of their memory addresses. A typical node consists of two attributes:
- data – the actual value stored in the node.
- pointer – a reference to the next node in the list.
Here’s the basic structure of a node in C:
struct Node {
int data;
struct Node *next;
};
The data
field holds the value assigned to the node (an integer in this case). And the next
pointer stores the address of the next node, allowing traversal through the list.
Since a linked list relies on pointers for navigation, overriding the next pointer of a node without preserving its original reference can break the chain, making it impossible to access subsequent nodes. This is why proper pointer management is crucial in linked lists (250204123024).
Here’s a minimal example of a linked list with three nodes (1 -> 2 -> 3):
#include <stdio.h>
#include <stdlib.h>
// Define a Node structure
typedef struct Node {
int data;
struct Node *next;
} Node;
int main(int argc, char **argv) {
// Allocate memory for the head node and check for NULL
Node *head = malloc(sizeof(Node));
// Initialize first node
head->data = 1;
head->next = malloc(sizeof(Node));
// Initialize second node
head->next->data = 2;
head->next->next = malloc(sizeof(Node));
// Initialize third node
head->next->next->data = 3;
head->next->next->next = NULL; // End of list
// Traverse and print the list
Node *curr = head;
while (curr) {
printf("%d\n", curr->data);
curr = curr->next;
}
// Free allocated memory
curr = head;
while (curr) {
Node *temp = curr->next;
free(curr);
curr = temp;
}
head = NULL; // Avoid dangling pointer
return 0;
}