Stacks Using Linked Lists
#include<stdio.h>
#include<stdlib.h>
typedef struct snode *sptr;
struct snode
{
int data;
sptr next;
};
sptr top;
void slpush(int x)
{
sptr new;
new=(sptr)malloc(sizeof(struct snode));
new->data=x;
new->next=NULL;
if(top==NULL)
{
top=new;
}
else
{
new->next=top;
top=new;
}
}
int slpop()
{
int x;
sptr ptr;
if(top==NULL)
{
printf("underflow exists.deletion not possible");
return(-1);
}
x=top->data;
ptr=top;
top=top->next;
free(ptr);
return(x);
}
int slpeep()
{
int x;
if(top==NULL)
{
printf("underflow exists.deletion not possible");
return(-1);
}
x=top->data;
return(x);
}
void sltraverse()
{ sptr p;
if(top==NULL)
{
printf("stack is empty \t");
return;
}
for(p=top;p!=NULL;p=p->next)
printf(" %d\t",p->data);
}
void main()
{
int x, choice;
top=NULL;
while(1)
{ printf("menu 1:push 2: pop 3:peep4: exit");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("enter element to be inserted");
scanf("%d",&x);
slpush(x);
sltraverse();
break;
case 2:x=slpop();
printf("deleted element is %d",x);
printf("\t remaining stack is");
sltraverse();
break;
case 3: x=slpeep();
printf("top element is %d",x);
break;
default:exit(0);
}
}
}