You are on page 1of 7

NAME:- ANUPAM SUR

REG.NO: 16MCA0156

REVERSING A SINGLY LINKED LIST USING RECURSIVE METHOD :


#include<stdio.h>
#include<malloc.h>
struct node{
int data;
struct node *next;
}*start=NULL;
void insert(){
struct node *x,*y;
x=(struct node *)malloc(sizeof(struct node));
printf("\nEnter data:");
scanf("%d",&x->data);
x->next=NULL;
if(start==NULL){
start=x;
}
else{
y=start;
while(y->next!=NULL){
y=y->next;
}
y->next=x;

}
}
display(){
struct node *x;
x=start;
while(x!=NULL){
printf("\t%d",x->data);
x=x->next;
}
}
recursiveDisplay(struct node *x){
if(x==NULL)
return;
recursiveDisplay(x->next);
printf("\t%d",x->data);

}
void main(){
int op;
while(1){
printf("\nEnter your option:");
printf("\n1.Insert data into Singly linked list.");
printf("\n2.Display the actual Singly linked list.");
printf("\n3.Display the reverse using the recursive function call.");
printf("\n0.Quit.");
scanf("%d",&op);
switch(op){
case 1 :

insert();

break;

case 2 :

display();

break;

case 3 :

recursiveDisplay(start);

case 0 :

exit(0);

default:

printf("\nOOPS!...Invalid option.");

break;

break;

}
}
}

================================================
====================

REVERSING OF A SINGLY LINKED LIST USING NON-RECURSIVE


METHOD:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *first=NULL,*last=NULL,*next,*pre,*cur,*temp;
void create()
{
cur=(struct node*) malloc(sizeof(struct node));
printf("enter first data to insert");
scanf("%d",&cur->data);

first=last=cur;
first->link=NULL;
}
void insert()
{
int pos,c;
cur=(struct node*) malloc(sizeof(struct node));
printf("enter data to insert and also its position");
scanf("%d%d",&cur->data,&pos);
if(pos==1)
{
cur->link=first;
first=cur;
}
else
{
c=1;
next=first;
while(c<pos)
{
pre=next;
next=next->link;
c++;
}
if(pre==NULL)
{
printf("Invalid position");
}

else
{
cur->link=pre->link;
pre->link=cur;
}
}
}
void display()
{
cur=first;
while(cur!=NULL)
{
printf(" %d\t",cur->data,cur);
cur=cur->link;
}
printf("\n");
}
void rev()
{
pre=NULL;
cur=first;
while(cur!=NULL)
{
next=cur->link;
cur->link=pre;
pre=cur;
cur=next;
}

first=pre;
}
void main()
{
int choice;
do
{
printf("Options are:
-\n1:Create\n2:Insert\n3:Display\n4:Reverse\n0:Exit\n");
printf("Enter your choice: - ");
scanf("%d",&choice);
switch(choice)
{
case 1:

create();
break;

case 2:
insert();
break;
case 3:
display();
break;
case 4:
rev();
break;
case 0:
exit(0);
default:
printf("wrong choice");
}

}
while(1);
}
================================================
==============================

You might also like