Skip to content
Home » Reversing of a singly linked list

Reversing of a singly linked list

Here our job is to make the last node of the list, the first node-second last node of the list, second node and so on. It’s all about updating the link part of the nodes and head pointer.

The idea is to update the link part of one node at a time which is pointed by head. This means if we want to update the link part of the 2nd node then we have to move our head pointer towards the 2nd node of the list . But before that, we have to keep a pointer that will point to the first node of the first node of the list.

Below is the code to reverse a linked list.

#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *head;
void create_linked_list(int element){
struct node *temp=malloc(sizeof(struct node));
temp->data=element;
temp->next=NULL;
if(head==NULL){
head=temp;
}
else{
struct node *ptr=head;
while(ptr->next!=NULL){
ptr=ptr->next;
}
ptr->next=temp;
}
}
void rev(){
struct node *prev,*link;
prev=NULL;
link=NULL;
while(head!=NULL){
link=head->next;
head->next=prev;
prev=head;
head=link;
}head=prev;
}
int main(){
create_linked_list(30);
create_linked_list(20);
create_linked_list(10);
create_linked_list(18);
rev();
//traversing the linked list
struct node *ptr=head;
while(ptr!=NULL){
printf("%d\t",ptr->data);
ptr=ptr->next;
}
}

OUTPUT:

18 10 20 30