Write a C program to reverse the linked list and also display the reversed linked list.
Linked List is a linear data structure in which nodes are connected with each other in a sequential manner. Each node contains the data and the address of the next node. The last node points to the NULL to terminate the list.
Example: 2 → 4 → 5 → NULL
Reverse Linked List is a linked list created to form a linked list by inverting the links within the list. The first node in the linked list is the last node in the linked list, and the last node is the first node.
Example:
Linked List before reversed:
1 → 2 → 3 → 4 → 5 → NULL
Reversed Linked List:
5 → 4 → 3 → 2 → 1 → NULL
To solve this problem, we need to follow the given steps:
1. Given the head pointer of the linked list.
2. Reverse the order of the linked list by updating the pointer of the node.
3. Update the head of the list.
4. Print the linked list before and after reversing it.
5. Exit.
This problem can be solved by many approaches, but here we are discussing the following approaches:
- Reverse a Linked List in C using Iterative Approach
- Reverse a Linked List in C using Stack
- Reverse a Linked List in C using Three Pointer
- Reverse a Linked List in C using Recursion
- Reverse a Linked List in C using Head Recursive Approach
- Reverse a Linked List in C using Tail Recursive Approach
- Another Linked List Example using Iterative Approach
The idea of this concept is to create a new list in reverse order. Create a node and insert it to the beginning of the list and update the head pointer.
Example:
Input:
Given the head of the linked list.
99 → 78 → 31 → 90 → 10 → NULL
Output:
Print the linked list before and after reversing it.
Linked List before reversed:
99 → 78 → 31 → 90 → 10 → NULL
Linked List after reversed:
10 → 90 → 31 → 78 → 99 → NULL
Here is a source code of the C Program to reverse a linked list using iterative approach. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Reverse a Linked List using iterative
*/
#include<stdio.h>
#include<malloc.h>
/*
* A linked list node
*/
struct node
{
int data;
struct node* next;
};
//Globally initialized head pointer
struct node* head = NULL;
//function prototyping
struct node* create_node(int);
void insert_begin(int);
void reverse_list();
void print();
int main()
{
/* Create some nodes and insert data into them */
insert_begin(10);
insert_begin(90);
insert_begin(31);
insert_begin(78);
insert_begin(99);
printf("Linked List before reversed: \n");
print();
reverse_list();
printf("\nLinked List after reversed: \n");
print();
return 0;
}
/*
* Creates a new node using the malloc function
*/
struct node* create_node(int data)
{
struct node* new_node = (struct node*) malloc (sizeof(struct node));
if (new_node == NULL)
{
printf("Memory can't be allocated for new node");
return NULL;
}
else
{
new_node -> data = data;
new_node -> next = NULL;
return new_node;
}
}
/*
* insert a new node at the beginning of the list
*/
void insert_begin(int data)
{
struct node* new_node = create_node(data);
if (new_node != NULL)
{
new_node -> next = head;
head = new_node;
}
}
/*
* reverse the linked list
*/
void reverse_list()
{
if (head == NULL)
{
return;
}
struct node* temp = head;
struct node* new_head = NULL;
// create new nodes and insert them beginning
while (temp != NULL)
{
struct node* new_node = create_node(temp->data);
new_node->next = new_head;
new_head = new_node;
temp = temp->next;
}
// update the head with the new head
head = new_head;
}
/*
* prints the linked list
*/
void print()
{
struct node* temp = head;
while (temp != NULL)
{
printf("%d --> ", temp->data);
temp = temp->next;
}
printf("NULL \n");
}
1. Creating some nodes with data and appending them at the start of the linked list.
2. Print the list before reversing the original list.
3. Iterate through the list from start to end node.
4. On every iteration, create a new node and store the data of the current iterating node.
5. Insert this node at the beginning of the list.
6. In the end, Update the head pointer to the new head pointer.
7. Print the reversed list.
Time Complexity: O(n)
Since the size of the list is n, where is the number of nodes. The traversing of the list is from the start node to the end node which is the size of the list.
Space Complexity: O(n)
Another list of the same size is created so the space complexity becomes the factor of n, which is the size of the list.
Linked List before reversed: 99 → 78 → 31 → 90 → 10 → NULL Linked List after reversed: 10 → 90 → 31 → 78 → 99 → NULL
In this method, the stack is implemented using the array. Stack is a linear data structure that stores the element in LIFO (Last In First Out) manner. Here the main concept is to store the all nodes of the list in Stack and then remove them one by one and insert it into the end of the list.
Here is a source code of the C Program to reverse the linked list using stack. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Reverse a Linked List using Stack
*/
#include<stdio.h>
#include<malloc.h>
/*
* A linked list node
*/
struct node
{
int data;
struct node* next;
};
//Globally initialized head pointer
struct node* head = NULL;
//function prototyping
struct node* create_node(int);
void insert_begin(int);
void reverse_list();
void print();
int main()
{
/* Create some nodes and insert data into them */
insert_begin(10);
insert_begin(90);
insert_begin(31);
insert_begin(78);
insert_begin(99);
printf("Linked List before reversed: \n");
print();
reverse_list();
printf("\nLinked List after reversed: \n");
print();
return 0;
}
/*
* Creates a new node using the malloc function
*/
struct node* create_node(int data)
{
struct node* new_node = (struct node*) malloc (sizeof(struct node));
if (new_node == NULL)
{
printf("Memory can't be allocated for new node");
return NULL;
}
else
{
new_node -> data = data;
new_node -> next = NULL;
return new_node;
}
}
/*
* insert a new node at the beginning of the list
*/
void insert_begin(int data)
{
struct node* new_node = create_node(data);
if (new_node != NULL)
{
new_node -> next = head;
head = new_node;
}
}
/*
* reverse the linked list
*/
void reverse_list()
{
if (head == NULL)
{
return;
}
//create a stack of size of 100
struct node* stack[100];
int top = -1;
struct node* temp = head;
// push list node into the stack
while (temp != NULL)
{
top += 1;
stack[top] = temp;
temp = temp->next;
}
// make a new head node
head = stack[top];
temp = stack[top];
// pop the nodes from the stack and insert them at the end of the last node
while (--top >= 0)
{
temp->next = stack[top];
temp = stack[top];
}
// terminate the list
temp->next = NULL;
}
/*
* prints the linked list
*/
void print()
{
struct node* temp = head;
while (temp != NULL)
{
printf("%d --> ", temp->data);
temp = temp->next;
}
printf("NULL \n");
}
1. Create some list nodes to perform the operations.
2. Print the list before reversing it.
3. Created a stack using the array.
4. Push the list nodes in Stack.
5. Update the head by the node which is at the top of the stack.
6. Remove one by one node from the stack and insert them at the end of the list.
7. Print the reversed list.
Time Complexity: O(n)
Since the size of the list is n, where is the number of nodes. The traversing of the list is from the start node to the end node which is the size of the list.
Space Complexity: O(n)
Since we have pushed all the nodes of the list in the stack so here n size of memory is used to store the list.
Linked List before reversed: 99 → 78 → 31 → 90 → 10 → NULL Linked List after reversed: 10 → 90 → 31 → 78 → 99 → NULL
The main concept of the iterative approach is to use the three different pointers. These pointers will point to the particular nodes on every iteration and change the address of the nodes.
Iterative Algorithm
Step 1: Take three pointers and initialize them as prev = NULL, next = NULL and curr = head.
Step 2: Iterate through the end of the list and follow the next steps.
Step 3: Store the address of the next node in the next pointer.
Step 4: Update the curr next to the prev pointer.
Step 5: Update the next pointer by curr pointer.
Step 6: Move the curr pointer to the next node.
Here is a source code of the C Program to reverse the linked list using three pointer. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Reverse a Linked List using three pointer
*/
#include<stdio.h>
#include<malloc.h>
/*
* A linked list node
*/
struct node
{
int data;
struct node* next;
};
//Globally initialized head pointer
struct node* head = NULL;
//function prototyping
struct node*create_node(int);
void insert_begin(int);
void reverse_list();
void print();
int main()
{
/* Create some nodes and insert data into them */
insert_begin(10);
insert_begin(90);
insert_begin(31);
insert_begin(78);
insert_begin(99);
printf("Linked List before reversed: \n");
print();
reverse_list();
printf("\nLinked List after reversed: \n");
print();
return 0;
}
/*
* Creates a new node using the malloc function
*/
struct node* create_node(int data)
{
struct node* new_node = (struct node*) malloc (sizeof(struct node));
if (new_node == NULL)
{
printf("Memory can't be allocated for new node");
return NULL;
}
else
{
new_node -> data = data;
new_node -> next = NULL;
return new_node;
}
}
/*
* insert a new node at the beginning of the list
*/
void insert_begin(int data)
{
struct node* new_node = create_node(data);
if (new_node != NULL)
{
new_node -> next = head;
head = new_node;
}
}
/*
* reverse the linked list
*/
void reverse_list()
{
struct node* prev = NULL, *curr = head, *next = NULL;
while (curr != NULL)
{
// store the next node
next = curr -> next;
// reverse the pointer of the current node
curr ->next = prev;
// move prev pointer to the current node
prev = curr;
// move current to its next node
curr = next;
}
//update the head pointer by prev pointer
head = prev;
}
/*
* prints the linked list
*/
void print()
{
struct node* temp = head;
while (temp != NULL)
{
printf("%d → ", temp->data);
temp = temp->next;
}
printf("NULL \n");
}
1. Creating some nodes with data and appending them at the start of the linked list.
2. Print the list before reversing the original list.
3. Take three pointers to update the node’s address.
4. Iterate through the list from start to end node.
5. On every iteration, store the next node of the current node.
6. Point the current node to its previous node.
7. Move the previous and current pointers to their next node.
8. In the end, Update the head pointer to the start node of the reversed list.
9. Print the reversed list.
Time Complexity: O(n)
Since the size of the list is n, where is the number of nodes. The traversing of the list is from the start node to the end node which is the size of the list.
Space Complexity: O(1)
There are only three pointers used to reverse the list which is a constant space and it is not depending on the size of the list.
Linked List before reversed: 99 → 78 → 31 → 90 → 10 → NULL Linked List after reversed: 10 → 90 → 31 → 78 → 99 → NULL
In this method, it uses recursive function & reverses the nodes in a linked list and displays the list. A linked list is an ordered set of data elements, each containing a link to its successor. This program makes each data element to link to its predecessor.
Here is the source code of the C program to reverse the nodes and display the linked list. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* Recursive C program to reverse nodes of a linked list and display
* them
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void print_reverse_recursive (struct node *);
void print (struct node *);
void create_new_node (struct node *, int );
//Driver Function
int main ()
{
struct node *head = NULL;
insert_new_node (&head, 1);
insert_new_node (&head, 2);
insert_new_node (&head, 3);
insert_new_node (&head, 4);
printf ("LinkedList : ");
print (head);
printf ("\nLinkedList in reverse order : ");
print_reverse_recursive (head);
printf ("\n");
return 0;
}
//Recursive Reverse
void print_reverse_recursive (struct node *head)
{
if (head == NULL)
{
return;
}
//Recursive call first
print_reverse_recursive (head -> next);
//Print later
printf ("%d ", head -> data);
}
//Print the linkedlist normal
void print (struct node *head)
{
if (head == NULL)
{
return;
}
printf ("%d ", head -> data);
print (head -> next);
}
//New data added in the start
void insert_new_node (struct node ** head_ref, int new_data)
{
struct node * new_node = (struct node *) malloc (sizeof (struct node));
new_node -> data = new_data;
new_node -> next = (*head_ref);
(*head_ref) = new_node;
}
Time Complexity: O(n)
The function is calling itself n times, which is the size of the linked list.
Space Complexity: O(n)
The maximum size of the function call is n, which stores each node of the list on every call onto the stack.
LinkedList : 4 3 2 1 LinkedList in reverse order : 1 2 3 4
Recursive functions use a stack to store the function calls. To solve this problem we recursively iterate the function calls to each node at the end of the list and then start the address to the previous node.
Recursive Algorithm
Step 1: Divide the linked list into two parts, the first part contains the first node, and the second part the remaining list.
Step 2: Call again the reverse_list_recursion() function by passing the head of the remaining list.
Step 3: Merge the remaining list to the first node and change the head pointer of the reversed list.
Step 4: Repeat the above steps until the entire list doesn’t get reversed.
Here is a source code of the C Program to reverse the linked list using recursion. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Reverse a Linked List using head recursive approach
*/
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node* next;
};
//Global head pointer
struct node* head = NULL;
//function prototyping
struct node*create_node(int);
void insert_begin(int);
struct node* reverse_recursion(struct node*);
void print();
int main()
{
/* Create some nodes and insert data into them */
insert_begin(10);
insert_begin(90);
insert_begin(31);
insert_begin(78);
insert_begin(99);
printf("Linked List before reversed: \n");
print();
head = reverse_recursion(head);
printf("\nLinked List after reversed: \n");
print();
return 0;
}
struct node* create_node( int data )
{
struct node* new_node = ( struct node* ) malloc (sizeof(struct node));
if (new_node == NULL)
{
printf("Memory can't be allocated for new node");
return NULL;
}
else
{
new_node -> data = data;
new_node -> next = NULL;
return new_node;
}
}
void insert_begin(int data)
{
struct node* new_node = create_node(data);
if (new_node != NULL)
{
new_node -> next = head;
head = new_node;
}
}
struct node* reverse_recursion(struct node* head)
{
// if only one node or the last node of the list
if (head == NULL || head->next == NULL)
{
return head;
}
struct node* new_head = reverse_recursion(head->next);
//update the next pointer of the current node
head -> next -> next = head;
//make the current node the last node
head -> next = NULL;
//return the new head node of the reversed list
return new_head;
}
void print()
{
struct node* temp = head;
while (temp != NULL)
{
printf("%d → ", temp->data);
temp = temp->next;
}
printf("NULL\n”);
}
1. Creating some nodes with data and inserting them at the start of the linked list.
2. Print the list before reversing the original list.
3. Call the function passing with the head node of the list.
4. The function checks whether the node is NULL or the last node of the list.
5. Pass the head of the remaining list on the next function call, which is the next node of the current node and stores the address of the returned new head node.
6. Update the next node by pointing it back to the current node.
7. Make the current node the last node.
8. Return new head of the list.
9. Print the reversed list.
Time Complexity: O(n)
The function is calling itself n times, which is the size of the linked list.
Space Complexity: O(n)
The maximum size of the function call is n, which stores each node of the list on every call onto the stack.
Linked List before reversed: 99 → 78 → 31 → 90 → 10 → NULL Linked List after reversed: 10 → 90 → 31 → 78 → 99 → NULL
In tail recursive solutions, we have to do operations before calling the recursive function. To reverse the list, call the function each time passing with the next node of the current node and the last node. Point the current node by the last node.
Here is a source code of the C Program to reverse the linked list using tail recursive approach. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Reverse a Linked List using tail recursion
*/
#include<stdio.h>
#include<malloc.h>
/*
* A linked list node
*/
struct node
{
int data;
struct node* next;
};
//Globally initialized head pointer
struct node* head = NULL;
struct node* last = NULL;
//function prototyping
struct node* create_node(int);
void insert_begin(int);
void reverse_list();
void print();
int main()
{
/* Create some nodes and insert data into them */
insert_begin(10);
insert_begin(90);
insert_begin(31);
insert_begin(78);
insert_begin(99);
printf("Linked List before reversed: \n");
print();
reverse_list(head, last);
printf("\nLinked List after reversed: \n");
print();
return 0;
}
/*
* Creates a new node using the malloc function
*/
struct node* create_node(int data)
{
struct node* new_node = (struct node*) malloc (sizeof(struct node));
if (new_node == NULL)
{
printf("Memory can't be allocated for new node");
return NULL;
}
else
{
new_node -> data = data;
new_node -> next = NULL;
return new_node;
}
}
/*
* insert a new node at the beginning of the list
*/
void insert_begin(int data)
{
struct node* new_node = create_node(data);
if (new_node != NULL)
{
new_node -> next = head;
head = new_node;
}
}
/*
* reverse the linked list
*/
void reverse_list(struct node* curr, struct node* last)
{
if (curr == NULL)
{
return;
}
struct node* next_node = curr->next;
curr->next = last;
last = curr;
//updating the head node
head = curr;
reverse_list(next_node, last);
}
/*
* prints the linked list
*/
void print()
{
struct node* temp = head;
while (temp != NULL)
{
printf("%d --> ", temp->data);
temp = temp->next;
}
printf("NULL \n");
}
1. Create some nodes and insert them at the beginning of the list.
2. Print the list before recursion.
3. Store the next node of the current node.
4. Update the next pointer of the current node by the last pointer.
5. Change the last pointer to the current pointer.
6. Update the head of the list by the current pointer.
7. Call again the same function by passing the next node of the current node and the last node.
8. Print the reversed list.
Time Complexity: O(n)
Since the size of the list is n, where is the number of nodes. The traversing of the list is from the start node to the end node which is the size of the list.
Space Complexity: O(n)
We are recursively iterating the list from start to end, which is the size of the list
Linked List before reversed: 99 → 78 → 31 → 90 → 10 → NULL Linked List after reversed: 10 → 90 → 31 → 78 → 99 → NULL
Here is a source code of the C Program to reverse a linked list. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Reverse a Linked List
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *next;
};
void create(struct node **);
void reverse(struct node **);
void release(struct node **);
void display(struct node *);
int main()
{
struct node *p = NULL;
int n;
printf("Enter data into the list\n");
create(&p);
printf("Displaying the nodes in the list:\n");
display(p);
printf("Reversing the list...\n");
reverse(&p);
printf("Displaying the reversed list:\n");
display(p);
release(&p);
return 0;
}
void reverse(struct node **head)
{
struct node *p, *q, *r;
p = q = r = *head;
p = p->next->next;
q = q->next;
r->next = NULL;
q->next = r;
while (p != NULL)
{
r = q;
q = p;
p = p->next;
q->next = r;
}
*head = q;
}
void create(struct node **head)
{
int c, ch;
struct node *temp, *rear;
do
{
printf("Enter number: ");
scanf("%d", &c);
temp = (struct node *)malloc(sizeof(struct node));
temp->num = c;
temp->next = NULL;
if (*head == NULL)
{
*head = temp;
}
else
{
rear->next = temp;
}
rear = temp;
printf("Do you wish to continue [1/0]: ");
scanf("%d", &ch);
} while (ch != 0);
printf("\n");
}
void display(struct node *p)
{
while (p != NULL)
{
printf("%d\t", p->num);
p = p->next;
}
printf("\n");
}
void release(struct node **head)
{
struct node *temp = *head;
*head = (*head)->next;
while ((*head) != NULL)
{
free(temp);
temp = *head;
(*head) = (*head)->next;
}
}
Enter data into the list Enter number: 1 Do you wish to continue [1/0]: 1 Enter number: 2 Do you wish to continue [1/0]: 1 Enter number: 3 Do you wish to continue [1/0]: 1 Enter number: 4 Do you wish to continue [1/0]: 1 Enter number: 5 Do you wish to continue [1/0]: 0 Displaying the nodes in the list: 1 2 3 4 5 Reversing the list... Displaying the reversed list: 5 4 3 2 1
To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.
- Check Programming Books
- Apply for Computer Science Internship
- Check Data Structure Books
- Practice Design & Analysis of Algorithms MCQ
- Check Computer Science Books