Thursday, May 19, 2016

WAP to create stack using link list

#include<stdio.h>
#include<conio.h>
struct node
{
int n;
struct node *next;
}*top=NULL,*temp;
void push(int x)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->n=x;
if(top==NULL)
temp->next=NULL;
else
temp->next=top;
top=temp;
}
int pop()
{
if(top==NULL)
{
printf("Stack is empty");
return;
}
temp=top;
top=temp->next;
return temp->n;
}
int peep(int p)
{
int i;
if(top==NULL)
{
printf("Stack is empty");
return;
}
temp=top;
for(i=0;i<p-1 && temp!=NULL;i++)
temp=temp->next;
if(temp!=NULL)
return temp->n;
else
printf("Position not found");
}
void change(int x,int p)
{
int i;
if(top==NULL)
{
printf("Stack is empty");
return;
}
temp=top;
for(i=0;i<p-1 && temp!=NULL;i++)
temp=temp->next;
if(temp!=NULL)
temp->n=x;
else
printf("Position not found");
}
void display()
{
if(top==NULL)
{
printf("Stack is empty");
return;
}
temp=top;
while(temp!=NULL)
{
printf("\n%d",temp->n);
temp=temp->next;
}
}
void main()
{
int x,p,ch;
clrscr();
do
{
printf("\n1.Push");
printf("\n2.Pop");
printf("\n3.Peep");
printf("\n4.Change");
printf("\n5.Display");
printf("\n6.Exit");
printf("\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter value:");
scanf("%d",&x);
push(x);
break;
case 2:
x=pop();
printf("\nDeleted value is: %d",x);
break;
case 3:
printf("\nEnter position: ");
scanf("%d",&p);
x=peep(p);
printf("\nValue at position %d is: %d",p,x);
break;
case 4:
printf("\nEnter value: ");
scanf("%d",&x);
printf("\nEnter position: ");
scanf("%d",&p);
change(x,p);
break;
case 5:
display();
break;
case 6:
printf("\nThank you");
break;
default:
printf("\nWorng choice");
}
}while(ch!=6);
getch();
}

No comments:

Post a Comment