Data Structures & Algorithms · A Beginner's Guide
Introduction to Linked Lists — Creation and Traversal
From arrays to nodes, pointers, linked-list creation, and traversal in C.
Earlier, we looked at arrays, which are data structures where elements are stored in contiguous memory locations. Here, we shall look at another data structure where elements need not be stored in contiguous memory locations. This data structure is called a linked list.
At a glance · Contents
Click a topic to jump to that section.
- Introduction: From Arrays to Linked Lists
- Structure of Each Node of a Linked List
- Advantages of Linked Lists over Arrays
- Advantages of Arrays over Linked Lists
- C Program: Create and Display a Linked List
1. Introduction: From Arrays to Linked Lists
There are 3 elements in this array, having the string data values: “Rama”, “Krishna”, “Govinda”.
Array A: elements are stored one after another
Note that the data values are stored in contiguous memory locations.
Each element is allocated 16 bytes of memory in this illustration. The elements are stored one after the other in contiguous memory locations.
-
A[0]occupies the address range 1200 to 1215. -
A[1]occupies the address range 1216 to 1231. -
A[2]occupies the address range 1232 to 1247. - If there were an
A[3], it would occupy the address range 1248 to 1263.
Note: The addresses are illustrative. Here, we are imagining something like
char A[3][16]. So each array element is allotted a 16-byte block, even though the actual stored string may use fewer bytes. The purpose here is to show that the array elements occupy contiguous memory locations.
A linked list differs from an array in that the elements, called nodes, need not be stored in contiguous memory locations.
Linked-list nodes may occupy different memory locations
The first node, “Rama”, is stored at address 1200. The 2nd node is at 1104, and the 3rd node at 1264.
As we can see, the nodes are not stored in contiguous memory locations, unlike arrays.
Note: The addresses above are only examples to illustrate non-contiguous storage in a linked list.
2. Structure of Each Node of a Linked List
Question: In arrays, we can easily compute the memory location where a particular element is stored, from the starting address of the array.
For example, consider an array A which starts at address 1400. Each element is allocated 8 bytes of storage. Therefore, we can confidently say that element A[i] is stored starting at address 1400 + (8 × i).
Therefore, in order to access (read the value, or modify, or whatever) element A[i], we can directly go to memory location 1400 + (8 × i).
What about linked lists? Since the nodes are not stored in contiguous locations, and seem to be stored at arbitrary locations, how would we access any specific node?
Answer: We make each node point to the next node; that is, each node stores the address of the next node.
Each node has two fields or two members:
- data — this is what we saw earlier itself; for example, “Rama”, “Krishna”, etc.
- next pointer — pointer to the next node in the linked list; that is, the memory address of the next node.
So, the individual nodes in a linked list are “linked” by way of the next pointer field, which is present in every node.
Three nodes linked by their next pointers
Each node in the illustration above has a data value and a next pointer. By means of the next pointer, we can go from one node to the next.
There is no node after node 3. Hence, the next pointer is marked as NULL, signifying the last node of the linked list.
What exactly is stored in each next pointer?
The same nodes, now showing the stored addresses
- Node 1 is stored starting at memory address 1200.
- The next pointer field of node 1 has the address 1104, signifying that node 2 is stored at that location.
- The next pointer field of node 2 has the address 1264, indicating that node 3 is stored at that location.
- Node 3 is the last node in the list. Hence, the next pointer field of node 3 is represented as NULL.
In linked lists, there is typically a head pointer pointing to the first node of the list. We shall explain this further in the C program below.
3. Advantages of Linked Lists over Arrays
Question: Why do we need linked lists? Are arrays not sufficient?
Answer:
1. Efficient insertion and deletion at the beginning
Let's say we want to insert an element at index 0 of an array already having several elements. We would need to shift all elements (to the right) to insert this element. Hence, insertion takes O(n) time.
Similarly, deletion at the beginning of an array also takes O(n) time.
Array: insert at the beginning
Shift existing elements to the right before placing the new element. Time: O(n).
Linked list: insert at the beginning
Update the new node's next pointer and head. Time: O(1), when the new node is available.
In contrast, inserting a node at the beginning of a linked list takes O(1) time. The same goes for deleting a node at the beginning.
To insert a node at the beginning, we simply need to update the next pointer of a single node (and also need to update the head pointer, which we shall explain later).
Similarly, deletion at the beginning of the list involves only updating a next pointer and the head pointer.
Hence, for insertions and deletions, linked lists are much more efficient than ordinary arrays.
Important distinction: The O(1) advantage applies to insertion and deletion at the beginning (and certain positions where the relevant pointers are already available). Finding an arbitrary position first may take O(n) time.
2. No requirement for one large contiguous memory block
Array elements are stored in contiguous memory locations. Hence, in order to accommodate a very large array, we need a sufficiently large empty block of memory.
In contrast, linked-list nodes need not be stored in contiguous memory locations. Hence, it is easier to accommodate individual nodes at various suitable memory locations.
3. Convenient dynamic growth and shrinking
For ordinary arrays in languages like C, the size of the array (that is, the number of elements) is usually specified at the time of creation itself. Dynamically extending the array (that is, adding more elements than the capacity) is not that simple.
Linked lists can readily, easily dynamically grow or shrink. No need to allocate any space beforehand.
Note: Languages like C++ and Python provide vectors and lists, which are arrays that can be dynamically resized. (In C++, the corresponding container is
vector; in Python, it islist.)
4. Advantages of Arrays over Linked Lists
Question: So, linked lists appear quite advantageous compared to arrays. Why then use arrays at all? Are not linked lists sufficient?
Answer: Advantages of arrays over linked lists:
1. Direct access to elements through their indices
Array elements are stored in contiguous memory locations. Hence, we know that the address of an element at index i can be directly computed from the base address of the array and the size of an element.
Example: array A begins at address 1400, with 8 bytes per element
Address of A[i] = 1400 + (8 × i)
Address of element at index i = (Base address of array) + (i × size of an element)
Thus, accessing A[i] takes O(1) time.
In contrast, to access a node at index i of a linked list, we must start at the head and traverse node-by-node until we reach the desired node. Therefore, accessing an arbitrary node in a linked list takes O(n) time in the worst case.
2. Less memory overhead
In arrays, we mainly just store the data values.
In contrast, in linked lists, we also need to store a pointer (the next pointer) along with the data, for every node. Plus, padding may also be involved. Hence, more memory per node is required.
For example, in a 64-bit system where integer size is 4 bytes and pointer size is 8 bytes:
Array element
data · 4 bytes
Exactly 4 bytes per int element
Linked-list node
data 4 B + pointer 8 B / + padding 4 B
Typically 16 bytes per node, excluding allocator overhead
Hence, for the same number of integer data values, a linked list will generally require more memory than an ordinary array.
3. Much more cache-friendly
Array elements are stored in contiguous memory locations. When the CPU reads one element, it loads nearby elements into its cache as well.
Hence, traversing an array can be done very quickly.
In contrast, in a linked list, the nodes are scattered at different memory locations. Hence, cache performance is not that good.
Therefore, even though traversal takes theoretically O(n) time for both arrays and linked lists, it is quite faster in practice for arrays than linked lists.
4. Binary search on sorted arrays
Binary search, which allows for very efficient O(log n) searching, can be applied on sorted arrays (by repeatedly exploring the middle-index element and reducing the search space by half).
In contrast, there is no direct way to access the middle node of a linked list. Hence, conventional binary search won't be useful on linked lists.
5. Simpler to use
For example, consider the code to traverse an array and a linked list.
Array traversal and printing:
for (int i = 0; i < n; i++)
printf("%d ", A[i]);
Linked-list traversal and printing:
struct Node *curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
As we can see, the coding is much simpler in the case of arrays.
5. C Program: Create and Display a Linked List
We shall write a simple C program to create a linked list having 3 nodes, and then we'll display the contents of the list.
Each node of our list will store an integer data value. And we already know that each node stores a pointer to the next node in the list.
We'll use the struct data type for each node. It will have two members: an int data value, and a pointer to the next node of the list.
struct Node {
int data;
struct Node *next;
};
next is the pointer to the next node of the list. That is, next stores the memory address of the next node in the list.
Each node in the list is of type struct Node. Therefore, next is a pointer of type struct Node *.
For linked lists, dynamic memory allocation is typically used. In C, we do this using malloc(), which is from stdlib.h.
At times, when we use malloc() to dynamically allocate memory, memory allocation may fail. We check for that, and we release any memory we may have previously allocated dynamically, and terminate the program with an error code.
After successfully allocating memory, we need to populate the nodes with data. For our simple program, we'll use any 3 integer values.
Then we need to link the nodes. We do this by properly assigning values to the next pointer of each node. Note that the next pointer of the last node has the value NULL, signifying the end of the list.
In linked lists, there is typically a head pointer, pointing to the first node of the list.
For displaying the contents of the list, we start from head, and traverse the list by means of the next pointer in each node. We traverse until we encounter NULL (indicating that there are no more nodes).
We assigned memory dynamically for 3 nodes using malloc(). So, after we've completed our use of the list, it is good programming practice to release the memory, to prevent memory leaks. We release the memory using free(), which is from stdlib.h.
Complete C program
//Program to illustrate the creation and traversal of a simple linked list.
#include <stdio.h> //for printf()
#include <stdlib.h> //for malloc() [dynamic memory allocation] and free()
struct Node{ //struct to represent each node of the linked list.
int data; //each node has an int data value
struct Node *next; //pointer to the next node in the list.
};
int main()
{
//we shall create a simple linked list having 3 nodes.
struct Node *first, *second, *third, *head; //pointers to the 3 nodes;
//head is the pointer to the first node of the list.
//dynamically allocate memory for each node.
first = malloc(sizeof(struct Node));
second = malloc(sizeof(struct Node));
third = malloc(sizeof(struct Node));
//check if memory allocation failed. IF so, terminate the program.
if ((first == NULL) || (second == NULL) || (third == NULL))
{
printf("Memory allocation failed! Program terminating.\n");
//free any memory that may have allocated; free() is from stdlib.h.
free(first);
free(second);
free(third);
return 1; //error code to indicate that the program terminated midway.
}
//assign data values to the 3 nodes
first->data = 10; //assign some sample int values to the 3 nodes.
second->data = 5;
third->data = 20;
//make the nodes point from one to the next node.
first->next = second; //first node points to the second.
second->next = third; //second node points to the third.
third->next = NULL; //there is no node after the third node.
//make the head point to the first node.
head = first;
//linked list of 3 nodes has been successfully created and populated with data.
//now we shall display its contents.
struct Node *curr = head; //assigning a pointer for traversing the list.
while (curr != NULL) //while there are still nodes to explore in the list.
{
printf("%d", curr->data);
//for displaying arrow mark in between the values.
if (curr->next != NULL) //need not display arrow mark after last node.
printf(" --> ");
curr = curr->next; //move on to the next node of the list.
}
//release the allocated memory.
free(first);
free(second);
free(third);
return 0;
}
Output
10 --> 5 --> 20
In the event of allocation failure: The program instead displays
Memory allocation failed! Program terminating.and returns status code1.
Interactive visualizer: Create and traverse the list
Interactive version: Open the complete step-by-step visualizer on Sri Ramanuja Seva.
The diagram below is a static snapshot from the interactive visualizer. The original site provides the Next, Previous, Play/Pause and Reset controls.
Original visualizer instructions: Follow the actual operations of the C program, from allocation to traversal and memory release. Use Next, Previous, Play/Pause, or Reset.
The diagrams use illustrative node addresses. Since the program allocates memory dynamically, the actual addresses can vary from one execution to another.
The interactive demonstration uses the same three values (10, 5 and 20) and follows the same allocation, linking, traversal and release stages as the C program.
More on DSA
Originally published on Sri Ramanuja Seva. Visit the original article for the interactive linked-list visualizer.








Top comments (0)