#include
struct node
{
int data;
struct node *next;
};
typedef struct node node;
struct stack
{
node *top;
};
struct stack s;
node *getnode()
{
node *newn;
newn=(node *)malloc(sizeof(node));
return(newn);
}
void push(stack *s,int num)
{
node *newn;
newn=getnode();
newn->data=num;
if(s->top==NULL)
{
s->top=newn;
s->top->next=newn;
return;
}
newn->next=s->top->next;
s->top->next=newn;
}
int pop(stack *s)
{
node *temp=s->top->next;
int num;
if(s->top==NULL)
{
printf("\nthe stack is empty");
return(-1);
}
if(s->top->next==s->top)
{
s->top=NULL;
free(s->top);
return(1);
}
else
{
num=s->top->next->data;
s->top->next=temp->next;
free(temp);
return(num);
}
}
void display(stack *s)
{
node *cur=s->top->next;
if(s->top==NULL)
{
printf("\nstack is empty");
return;
}
while(cur!=s->top)
{
printf("\n %d",cur->data);
cur=cur->next;
}
printf("\n %d",cur->data);
}
main()
{
int ch,done=0,num;
stack s;
s.top=NULL;
while(!done)
{
printf("\n\n\n 1.PUSH 2.POP 3.DISPLAY 4.EXIT\n enter ur choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n enter the num: ");
scanf("%d",&num);
push(&s,num);
break;
case 2:
num=pop(&s);
if(num!=-1)
printf("\n%d deleted element",num);
break;
case 3:
display(&s);
break;
case 4:
done =1;
break;
}
}
}
No comments:
Post a Comment