Friday 25 September 2015

How to reverse a Linked List in C Language

                In most of the technical interviews, it is common question. Here we will see iterative way to reverse a singly linked list in C language. I have given complete C program which consists of  functions to insert elements into linked list, to reverse the linked list and to print list's elements on screen.
                 Go through the following code. I have given output at the end of this post.


 
Program: (linkedlistreversal.c)

#include<stdio.h>
#include<stdlib.h>
struct list
{
int value;
struct list *link;
};
typedef struct list node;

int i,n;

void inserttolist(node **sample,int n)
{
node *temp=NULL;
if(n>0)
{
temp = (node *)malloc(sizeof(node));
scanf("%d",&temp->value);
temp->link=NULL;
*sample=temp;
n=n-1;
inserttolist(&(*sample)->link,n);
}
else
{
return;
}
}

void printlist(node *sample)
{
if(sample != NULL)
{
printf("%d\n",sample->value);
printlist(sample->link);
}
else
{
return;
}
}

void reverselist(node **sample)
{
node *cur, *next, *temp;
if(*sample == NULL)
{
return;
}
cur= *sample;
next= cur->link;
cur->link = NULL;
while (next != NULL)
{
temp= next->link;
next->link = cur;
cur= next;
next= temp;
}
*sample = cur;
}

void main()
{
node *sample=NULL;

printf("Enter total number of elements of Linked List\n");
scanf("%d",&n);
printf("Enter %d elements of Linked List:\n",n);

inserttolist(&sample,n);

printf("Elements of Linked List are as follows:\n");
printlist(sample);

reverselist(&sample);

printf("Elements of Linked List in Reverse Order are as follows:\n");
printlist(sample);
}

How To Run:
To Compile:
>>>gcc linkedlistreversal.c

To Run:
>>>./a.out

Output: 




4 comments: