Summary: in this tutorial, you will learn about C linked list data structure and how to implement the most commonly used linked list operations.
Introduction to linked list data structure
A linked list is a data structure that consists of sequence of nodes. Each node is composed of two fields: data field and reference field which is a pointer that points to the next node in the sequence.
Each node in the list is also called an element. The reference field that contains a pointer which points to the next node is called next pointer or next link.
A head pointer is used to track the first element in the linked list, therefore, it always points to the first element.
The following picture illustrates a linked list
The linked list data structure is designed to be efficient for insertion or removal of elements from any position in the list. However other operations such as getting the last element or finding an element that stores specific data requires scanning most or all the elements in the list.
A linked list is also used to implement other data structure such as stack and queue.
C Linked List implementation
We can model a node of the linked list using a structure as follows:
typedef struct node{
int data;
struct node* next;
}
Code language: C++ (cpp)
The node structure has two members:
data
stores the informationnext
pointer holds the address of the next node.
Add a node at the beginning of the linked list
First, we declare a head pointer that always points to the first node of the list.
Code language: C++ (cpp)node* head;
To add a node at the beginning of the list:
First, we need to create a new node. We will need to create a new node each time we want to insert a new node into the list so we can develop a function that creates a new node and return it.
node* create(int data,node* next)
{
node* new_node = (node*)malloc(sizeof(node));
if(new_node == NULL)
{
printf("Error creating a new node.\n");
exit(0);
}
new_node->data = data;
new_node->next = next;
return new_node;
}
Code language: C++ (cpp)
Second, we need to point the next
pointer of the new node to the head
pointer and point the head
pointer to the new node. It works for both empty and non-empty linked list.
node* prepend(node* head,int data)
{
node* new_node = create(data,head);
head = new_node;
return head;
}
Code language: C++ (cpp)
The following picture illustrates how to insert a node when the list is empty:
The following picture illustrates how to insert a node at the beginning of a non-empty linked list:
Traverse the linked list
Sometimes we may want to traverse the linked list to get the data stored in each node for further manipulation e.g., display the node information. To traverse the linked list, we start from the first node, and move to the next node until we reach a NULL pointer.
To make the traverse()
function more general, we can add a function pointer that points to a function for linked list node manipulation as a parameter of the traverse()
function.
We define a call back function for manipulating a node of the linked list:
typedef void (*callback)(node* data);
Code language: C++ (cpp)
The following is the traverse()
function:
void traverse(node* head,callback f)
{
node* cursor = head;
while(cursor != NULL)
{
f(cursor);
cursor = cursor->next;
}
}
Code language: C++ (cpp)
Count the elements of the linked list
We can use the same traversing technique to count the number of elements in a linked list. See the following count()
function:
int count(node *head)
{
node *cursor = head;
int c = 0;
while(cursor != NULL)
{
c++;
cursor = cursor->next;
}
return c;
}
Code language: C++ (cpp)
Add a new node at the end of the linked list
To add a new node at the end of the linked list:
First, we need to find the last node of the list. Starting the first node which is indicated by the head
pointer, we traverse the list until the next pointer reaches NULL.
node *cursor = head;
while(cursor->next != NULL)
cursor = cursor->next;
Code language: C++ (cpp)
Second, we create a new node with the next
pointer points to NULL
, and the next
pointer of the cursor
points to the new node:
node* new_node = create(data,NULL);
cursor->next = new_node;
Code language: C++ (cpp)
Code language: C++ (cpp)
The following is the append()
function that adds a new node at the end of the linked list.
node* append(node* head, int data)
{
/* go to the last node */
node *cursor = head;
while(cursor->next != NULL)
cursor = cursor->next;
/* create a new node */
node* new_node = create(data,NULL);
cursor->next = new_node;
return head;
}
Code language: C++ (cpp)
Insert a new node after a particular node
To insert a new node after a particular node, we need to:
First, verify if the node exists in the list, we call this node is prev
node
node *cursor = head;
while(cursor != prev)
cursor = cursor->next;
Code language: C++ (cpp)
If it exists, we point the next pointer of the new node to the next node that the next pointer of the prev
node points to, and point the next pointer of the prev
node to the new node.
Code language: C++ (cpp)node* new_node = create(data,cursor->next); cursor->next = new_node;
The following picture illustrates how to insert a new node after a particular node in the linked list:
The insert_after()
function is as follows:
/*
insert a new node after the prev node
*/
node* insert_after(node *head, int data, node* prev)
{
/* find the prev node, starting from the first node*/
node *cursor = head;
while(cursor != prev)
cursor = cursor->next;
if(cursor != NULL)
{
node* new_node = create(data,cursor->next);
cursor->next = new_node;
return head;
}
else
{
return NULL;
}
}
Code language: C++ (cpp)
Insert a new node before a particular node
To insert a new node before a particular node named nxt
we need to:
- First, if the
nxt
node is the first node, we can call theprepend()
function to add a new node at the beginning of the list, otherwise, we find the previous node of thenxt
node, suppose it is thecursor
node. - Second, point the
next
pointer of the new node to the node that thenext
pointer of thecursor
points to and point thenext
pointer of thecursor
to the new node.
The following picture illustrates how to insert a node before a particular node:
The following is the insert_before()
function that inserts a new node before a particular node in the linked list:
node* insert_before(node *head, int data, node* nxt)
{
if(nxt == NULL || head == NULL)
return NULL;
if(head == nxt)
{
head = prepend(head,data);
return head;
}
/* find the prev node, starting from the first node*/
node *cursor = head;
while(cursor != NULL)
{
if(cursor->next == nxt)
break;
cursor = cursor->next;
}
if(cursor != NULL)
{
node* new_node = create(data,cursor->next);
cursor->next = new_node;
return head;
}
else
{
return NULL;
}
}
Code language: C++ (cpp)
Search for a node
To search for a node that stores a given data, we scan the whole list and return the first node that stores the searched data. The following illustrates the search function:
node* search(node* head,int data)
{
node *cursor = head;
while(cursor!=NULL)
{
if(cursor->data == data)
return cursor;
cursor = cursor->next;
}
return NULL;
}
Code language: C++ (cpp)
The search()
function returns NULL
if no node stores the input data.
Sort a linked list using insertion sort
We can sort a linked list using the insertion sort algorithm. The following is the insertion_sort()
function that sorts a linked list:
node* insertion_sort(node* head)
{
node *x, *y, *e;
x = head;
head = NULL;
while(x != NULL)
{
e = x;
x = x->next;
if (head != NULL)
{
if(e->data > head->data)
{
y = head;
while ((y->next != NULL) && (e->data> y->next->data))
{
y = y->next;
}
e->next = y->next;
y->next = e;
}
else
{
e->next = head;
head = e ;
}
}
else
{
e->next = NULL;
head = e ;
}
}
return head;
}
Code language: C++ (cpp)
Reverse linked list
To reverse a linked list, you change the next
pointer of each node from the next node to the previous node. The following reverse()
function reverses a linked list.
node* reverse(node* head)
{
node* prev = NULL;
node* current = head;
node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
return head;
}
Code language: C++ (cpp)
Delete a node from the front of the linked list
To delete a node from the front of the linked list is relatively simple. We point the head
to the next node and remove the node that the head
pointed to.
Notice that if the list has only one node, we should set the head
pointer to NULL
.
The following is the remove_front()
function:
node* remove_front(node* head)
{
if(head == NULL)
return NULL;
node *front = head;
head = head->next;
front->next = NULL;
/* is this the last node in the list */
if(front == head)
head = NULL;
free(front);
return head;
}
Code language: C++ (cpp)
Delete a node from the back of the linked list
To remove a node from the back of the linked list, we need to:
- Use two pointers:
cursor
andback
to track the node. - Start from the first node until the
cursor
pointer reaches the last node and theback
pointer reaches the node before the last node. - Set the
next
pointer of theback
toNULL
and delete the node that thecursor
points to. - If the node has only 1 element, set the
head
pointer toNULL
before removing the node.
See the following picture:
The following is the function to remove a node from the back of the linked list:
node* remove_back(node* head)
{
if(head == NULL)
return NULL;
node *cursor = head;
node *back = NULL;
while(cursor->next != NULL)
{
back = cursor;
cursor = cursor->next;
}
if(back != NULL)
back->next = NULL;
/* if this is the last node in the list*/
if(cursor == head)
head = NULL;
free(cursor);
return head;
}
Code language: C++ (cpp)
Delete a node in the middle of the linked list
To delete a node in the middle of the linked list:
If the node is the first node, call remove_front()
function to remove it.
If the node is the last node, call remove_back()
function to remove it.
If the node is in the middle of the list:
- Traverse from the first node, use the
cursor
pointer to point to the node before the node that needs to be removed e.g., in the picture, the node that needs to be removed is2
and thecursor
pointer points to node5
. - Use a
tmp
pointer to point to the node that needs to be removed. - Set the
next
pointer of thecursor
point to the node that thenext
pointer of thetmp
points to. - Remove the node that the
tmp
pointer points to.
The following picture illustrates how to delete a node in the middle of the linked list:
The following is the function that can be used to remove any node in the linked list:
node* remove_any(node* head,node* nd)
{
/* if the node is the first node */
if(nd == head)
{
head = remove_front(head);
return head;
}
/* if the node is the last node */
if(nd->next == NULL)
{
head = remove_back(head);
return head;
}
/* if the node is in the middle */
node* cursor = head;
while(cursor != NULL)
{
if(cursor->next = nd)
break;
cursor = cursor->next;
}
if(cursor != NULL)
{
node* tmp = cursor->next;
cursor->next = tmp->next;
tmp->next = NULL;
free(tmp);
}
return head;
}
Code language: C++ (cpp)
Delete the whole linked list
It is important to remove all nodes of the linked list when you no longer use it. The following dispose()
function releases memory allocated for all the nodes in a linked list:
void dispose(node *head)
{
node *cursor, *tmp;
if(head != NULL)
{
cursor = head->next;
head->next = NULL;
while(cursor != NULL)
{
tmp = cursor->next;
free(cursor);
cursor = tmp;
}
}
}
Code language: C++ (cpp)
C Linked List Program
We can write a program to test the linked list functions that we’ve developed in the above section.
/*
& File : main.c
* Author : learnc.net
* Purpose : C Linked List Data Structure
* Copyright: @ learnc.net
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node* next;
} node;
typedef void (*callback)(node* data);
/*
create a new node
initialize the data and next field
return the newly created node
*/
node* create(int data,node* next)
{
node* new_node = (node*)malloc(sizeof(node));
if(new_node == NULL)
{
printf("Error creating a new node.\n");
exit(0);
}
new_node->data = data;
new_node->next = next;
return new_node;
}
/*
add a new node at the beginning of the list
*/
node* prepend(node* head,int data)
{
node* new_node = create(data,head);
head = new_node;
return head;
}
/*
add a new node at the end of the list
*/
node* append(node* head, int data)
{
if(head == NULL)
return NULL;
/* go to the last node */
node *cursor = head;
while(cursor->next != NULL)
cursor = cursor->next;
/* create a new node */
node* new_node = create(data,NULL);
cursor->next = new_node;
return head;
}
/*
insert a new node after the prev node
*/
node* insert_after(node *head, int data, node* prev)
{
if(head == NULL || prev == NULL)
return NULL;
/* find the prev node, starting from the first node*/
node *cursor = head;
while(cursor != prev)
cursor = cursor->next;
if(cursor != NULL)
{
node* new_node = create(data,cursor->next);
cursor->next = new_node;
return head;
}
else
{
return NULL;
}
}
/*
insert a new node before the nxt node
*/
node* insert_before(node *head, int data, node* nxt)
{
if(nxt == NULL || head == NULL)
return NULL;
if(head == nxt)
{
head = prepend(head,data);
return head;
}
/* find the prev node, starting from the first node*/
node *cursor = head;
while(cursor != NULL)
{
if(cursor->next == nxt)
break;
cursor = cursor->next;
}
if(cursor != NULL)
{
node* new_node = create(data,cursor->next);
cursor->next = new_node;
return head;
}
else
{
return NULL;
}
}
/*
traverse the linked list
*/
void traverse(node* head,callback f)
{
node* cursor = head;
while(cursor != NULL)
{
f(cursor);
cursor = cursor->next;
}
}
/*
remove node from the front of list
*/
node* remove_front(node* head)
{
if(head == NULL)
return NULL;
node *front = head;
head = head->next;
front->next = NULL;
/* is this the last node in the list */
if(front == head)
head = NULL;
free(front);
return head;
}
/*
remove node from the back of the list
*/
node* remove_back(node* head)
{
if(head == NULL)
return NULL;
node *cursor = head;
node *back = NULL;
while(cursor->next != NULL)
{
back = cursor;
cursor = cursor->next;
}
if(back != NULL)
back->next = NULL;
/* if this is the last node in the list*/
if(cursor == head)
head = NULL;
free(cursor);
return head;
}
/*
remove a node from the list
*/
node* remove_any(node* head,node* nd)
{
if(nd == NULL)
return NULL;
/* if the node is the first node */
if(nd == head)
return remove_front(head);
/* if the node is the last node */
if(nd->next == NULL)
return remove_back(head);
/* if the node is in the middle */
node* cursor = head;
while(cursor != NULL)
{
if(cursor->next == nd)
break;
cursor = cursor->next;
}
if(cursor != NULL)
{
node* tmp = cursor->next;
cursor->next = tmp->next;
tmp->next = NULL;
free(tmp);
}
return head;
}
/*
display a node
*/
void display(node* n)
{
if(n != NULL)
printf("%d ", n->data);
}
/*
Search for a specific node with input data
return the first matched node that stores the input data,
otherwise return NULL
*/
node* search(node* head,int data)
{
node *cursor = head;
while(cursor!=NULL)
{
if(cursor->data == data)
return cursor;
cursor = cursor->next;
}
return NULL;
}
/*
remove all element of the list
*/
void dispose(node *head)
{
node *cursor, *tmp;
if(head != NULL)
{
cursor = head->next;
head->next = NULL;
while(cursor != NULL)
{
tmp = cursor->next;
free(cursor);
cursor = tmp;
}
}
}
/*
return the number of elements in the list
*/
int count(node *head)
{
node *cursor = head;
int c = 0;
while(cursor != NULL)
{
c++;
cursor = cursor->next;
}
return c;
}
/*
sort the linked list using insertion sort
*/
node* insertion_sort(node* head)
{
node *x, *y, *e;
x = head;
head = NULL;
while(x != NULL)
{
e = x;
x = x->next;
if (head != NULL)
{
if(e->data > head->data)
{
y = head;
while ((y->next != NULL) && (e->data> y->next->data))
{
y = y->next;
}
e->next = y->next;
y->next = e;
}
else
{
e->next = head;
head = e ;
}
}
else
{
e->next = NULL;
head = e ;
}
}
return head;
}
/*
reverse the linked list
*/
node* reverse(node* head)
{
node* prev = NULL;
node* current = head;
node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
return head;
}
/*
display the menu
*/
void menu()
{
printf("--- C Linked List Demonstration --- \n\n");
printf("0.menu\n");
printf("1.prepend an element\n");
printf("2.append an element\n");
printf("3.search for an element\n");
printf("4.insert after an element\n");
printf("5.insert before an element\n");
printf("6.remove front node\n");
printf("7.remove back node\n");
printf("8.remove any node\n");
printf("9.sort the list\n");
printf("10.Reverse the linked list\n");
printf("-1.quit\n");
}
int main()
{
int command = 0;
int data;
node* head = NULL;
node* tmp = NULL;
callback disp = display;
menu();
while(1)
{
printf("\nEnter a command(0-10,-1 to quit):");
scanf("%d",&command);
if(command == -1)
break;
switch(command)
{
case 0:
menu();
break;
case 1:
printf("Please enter a number to prepend:");
scanf("%d",&data);
head = prepend(head,data);
traverse(head,disp);
break;
case 2:
printf("Please enter a number to append:");
scanf("%d",&data);
head = append(head,data);
traverse(head,disp);
break;
case 3:
printf("Please enter a number to search:");
scanf("%d",&data);
tmp = search(head,data);
if(tmp != NULL)
{
printf("Element with value %d found.",data);
}
else
{
printf("Element with value %d not found.",data);
}
break;
case 4:
printf("Enter the element value where you want to insert after:");
scanf("%d",&data);
tmp = search(head,data);
if(tmp != NULL)
{
printf("Enter the element value to insert after:");
scanf("%d",&data);
head = insert_after(head,data,tmp);
if(head != NULL)
traverse(head,disp);
}
else
{
printf("Element with value %d not found.",data);
}
break;
case 5:
printf("Enter the element value where you want to insert before:");
scanf("%d",&data);
tmp = search(head,data);
if(tmp != NULL)
{
printf("Enter the element value to insert before:");
scanf("%d",&data);
head = insert_before(head,data,tmp);
if(head != NULL)
traverse(head,disp);
}
else
{
printf("Element with value %d not found.",data);
}
break;
case 6:
head = remove_front(head);
if(head != NULL)
traverse(head,disp);
break;
case 7:
head = remove_back(head);
if(head != NULL)
traverse(head,disp);
break;
case 8:
printf("Enter the element value to remove:");
scanf("%d",&data);
tmp = search(head,data);
if(tmp != NULL)
{
remove_any(head,tmp);
if(head != NULL)
traverse(head,disp);
}
else
{
printf("Element with value %d not found.",data);
}
break;
case 9:
head = insertion_sort(head);
if(head != NULL)
traverse(head,disp);
break;
case 10:
head = reverse(head);
if(head != NULL)
traverse(head,disp);
break;
}
}
dispose(head);
return 0;
}
Code language: C++ (cpp)
The following is the output when we ran the C linked list program above:
--- C Linked List Demonstration ---
0.menu
1.prepend an element
2.append an element
3.search for an element
4.insert after an element
5.insert before an element
6.remove front node
7.remove back node
8.remove any node
9.sort the list
10.Reverse the linked list
-1.quit
Enter a command(0-10,-1 to quit):1
Please enter a number to prepend:1
1
Enter a command(0-10,-1 to quit):1
Please enter a number to prepend:3
3 1
Enter a command(0-10,-1 to quit):1
Please enter a number to prepend:2
2 3 1
Enter a command(0-10,-1 to quit):1
Please enter a number to prepend:5
5 2 3 1
Enter a command(0-10,-1 to quit):2
Please enter a number to append:6
5 2 3 1 6
Enter a command(0-10,-1 to quit):2
Please enter a number to append:9
5 2 3 1 6 9
Enter a command(0-10,-1 to quit):2
Please enter a number to append:8
5 2 3 1 6 9 8
Enter a command(0-10,-1 to quit):2
Please enter a number to append:0
5 2 3 1 6 9 8 0
Enter a command(0-10,-1 to quit):3
Please enter a number to search:2
Element with value 2 found.
Enter a command(0-10,-1 to quit):3
Please enter a number to search:4
Element with value 4 not found.
Enter a command(0-10,-1 to quit):4
Enter the element value where you want to insert after:3
Enter the element value to insert after:4
5 2 3 4 1 6 9 8 0
Enter a command(0-10,-1 to quit):5
Enter the element value where you want to insert before:1
Enter the element value to insert before:-1
5 2 3 4 -1 1 6 9 8 0
Enter a command(0-10,-1 to quit):6
2 3 4 -1 1 6 9 8 0
Enter a command(0-10,-1 to quit):7
2 3 4 -1 1 6 9 8
Enter a command(0-10,-1 to quit):8
Enter the element value to remove:1
2 3 4 -1 6 9 8
Enter a command(0-10,-1 to quit):9
-1 2 3 4 6 8 9
Enter a command(0-10,-1 to quit):10
9 8 6 4 3 2 -1
Enter a command(0-10,-1 to quit):-1
Code language: CSS (css)
In this tutorial, we have introduced you to C linked list and how to implement commonly used linked list operations such as prepend, append, traverse, count, insert, remove, sort, and dispose.