Monday, September 12, 2016

Code to Reverse A Singly Link List in C

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct node
{
int data;
struct node *next;
};
struct node *start=NULL;
struct node *temp=NULL;

void insert()
{
int lData=0;
struct node *temp1;
printf("Please enter data:\t");
scanf("%d",&lData);
temp=malloc(sizeof(struct node *));
temp1=start;

if(temp1 == NULL )
{
start=temp;
temp->data=lData;
temp->next=NULL;
}
else
{
printf("here1\n");
while(temp1->next != NULL)
{
temp1=temp1->next;
}
temp1->next=temp;
temp->data=lData;
temp->next=NULL;
}
}
void display()
{
struct node *temp1=start;
if(temp == NULL )
printf("Linked list is empty\n");
else
{
while(temp1->next != NULL )
{
printf("Final Element is [%d]\n",temp1->data);
temp1=temp1->next;
}
printf("Final Element is [%d]\n",temp1->data);
}
}
void reverse()
{
struct node *prev=NULL;
struct node *current=start ;
struct node *temp;
while(current != NULL)
{
temp=current->next;
current->next=prev;
prev=current;
current=temp;
}
start=prev;
}
int main()
{
int choice;
while(1)
{
printf(" 1. For Insert into link list\n 2. Display link list\n 3. Reverse a link list\n 4. Exit\n\n Enter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
reverse();
break;
case 4:
exit(0);
break;
default:
printf("Invalid choice\n");
break;
}
}
return 0;
}

No comments:

Post a Comment