Program to reverse a singly linked list
A singly linked list is a type of list in which there is a pointer which point the next node in the list.
There is a head pointer which tell that the starting point of the list is fixed
functions used are:
User defined functions are:-
a. create();
b.display();
c.reverse();
Library functions-:
a,getch();
b.clrscr();
c.printf();
d.scanf();
//header files are include d
#include<stdio.h>
#include<conio.h>
//creation of structure
typedef struct list
{
int data;
struct list *next;
}node;
node *start=NULL;
node *creat(node*);
node *display(node*);
node *reverse(node*);
//start of program
void main()
{
int option,c=0;
clrscr();
do
{
printf("\n Main Menu");
printf("\n1:Creat list");
printf("\n2:Display list");
printf("\n3:reverse");
printf("\n0:Exit\n");
printf("\nEnter your option:-");
scanf("%d",&option);
switch(option)
{
case 1:start=creat(start);
printf("\nlinked list created");
break;
case 2:start=display(start);
break;
case 3:start=reverse(start);
printf("linked list reversed");
break;
case 0:
exit(0);
}
}
while(option!=0);
getch();
}
node *creat(node *start)
{
node *ptr,*newnode;
int num;
printf("Enter data,pres 999 to exit:-");
scanf("%d",&num);
while(num!=999)
{
newnode=(node*)malloc(sizeof(node));
newnode->data=num;
if(start==NULL)
{
newnode->next=NULL;
start=newnode;
}
else
{
ptr=start;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=newnode;
newnode->next=NULL;
}
printf("Enter another data:-");
scanf("%d",&num);
}
return start;
}
node* display(node* start)
{
node *ptr;
ptr=start;
while(ptr!=NULL)
{
printf("\%d->",ptr->data);
ptr=ptr->next;
}
return start;
}
node *reverse(node* start)
{
node *ptr,*preptr;
node *next;
ptr=start;
{
while(ptr!=NULL)
{
next=ptr->next;
ptr->next=preptr;
preptr=ptr;
ptr=next;
}
start=preptr;
}
return(start);
}
{
case 1:start=creat(start);
printf("\nlinked list created");
break;
case 2:start=display(start);
break;
case 3:start=reverse(start);
printf("linked list reversed");
break;
case 0:
exit(0);
}
}
while(option!=0);
getch();
}
node *creat(node *start)
{
node *ptr,*newnode;
int num;
printf("Enter data,pres 999 to exit:-");
scanf("%d",&num);
while(num!=999)
{
newnode=(node*)malloc(sizeof(node));
newnode->data=num;
if(start==NULL)
{
newnode->next=NULL;
start=newnode;
}
else
{
ptr=start;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=newnode;
newnode->next=NULL;
}
printf("Enter another data:-");
scanf("%d",&num);
}
return start;
}
node* display(node* start)
{
node *ptr;
ptr=start;
while(ptr!=NULL)
{
printf("\%d->",ptr->data);
ptr=ptr->next;
}
return start;
}
node *reverse(node* start)
{
node *ptr,*preptr;
node *next;
ptr=start;
{
while(ptr!=NULL)
{
next=ptr->next;
ptr->next=preptr;
preptr=ptr;
ptr=next;
}
start=preptr;
}
return(start);
}
Post a Comment