C source code for implementation of stacks using Linked List

, by Engineer's Vision

/* stacks using Linked List */

#include<stdio.h>
#include<conio.h>
typedef struct stack
{
int data;
struct stack *next;
}stack;
void initialize(stack **);
int empty(stack *);
int pop(stack **);
void push(stack **, int);
void print(stack *p);
void main()
{
stack *top;
int x,op;
initialize(&top);
clrscr();
do
{
printf("\n1.push \n2.pop \n3.print \n4.quit");
printf("\n enter your choice");
scanf("%d",&op);
switch(op)
{
case 1:
printf("enter a number");
scanf("%d",&x);
push(&top,x);
break;
case 2:
if(!empty(top))
{
x=pop(&top);
printf("\n popped value is=%d",x);
}
else printf("\n stack is empty");
break;
case 3:
print(top);
break;
}
}
while(op!=4);
}
void initialize(stack **t)
{
*t=NULL;
}
int empty(stack *top)
{
if(top==NULL)
return (1);
return (0);
}
void push(stack **t, int x)
{
stack *p;
p=(stack *)malloc(sizeof(stack));
p->data=x;
p->next=*t;
*t=p;
}
int pop(stack **t)
{
int x;
stack *p;
p=*t;
*t=p->next;
x=p->data;
free(p);
return(x);
}
void print(stack *p)
{
printf("\n");
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
}
}

0 comments: