Implementation of stack using Dynamic memory allocation

Tuesday, 3 December 2013

/* Implementation of stack using Dynamic memory allocation */

#include<stdio.h>
#include<conio.h>
typedef struct stack
{
int data;
struct stack *next;
} stack;
void init(stack **);
int empty(stack *);
char pop(stack **);
void push(stack **,int);
void print(stack *);
void main()
{
stack *TOP;
int x,op;
init(&TOP);
clrscr();
do
{
printf("\n1)Push\n2)Pop\n3)Print\n4)Quit");
printf("\nEnter Your Choice : ");
scanf("%d",&op);
switch(op)
{
case 1: printf("\nEnter a data : ");
scanf("%d",&x);
push(&TOP,x);
break;
case 2: if(!empty(TOP))
{
x=pop(&TOP);
printf("\nPopped data= %d",x);
}
else
printf("\nStack is empty ....");
break;
case 3: print(TOP);
break;
}
} while(op!=4);
}

void init(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;
}
char pop(stack **T)
{
int x;
stack * P;
P=*T;
*T=P->next;
x=P->data;
free(P);
return(x);
}
void print(stack *T)
{
printf("\n");
while (T!=NULL)
{
printf("%d ",T->data);
T=T->next;
}
}


OUTPUT:-

1)Push
2)Pop
3)Print
4)Quit
Enter Your Choice : 1

Enter a data : 45

1)Push
2)Pop
3)Print
4)Quit
Enter Your Choice : 1

Enter a data : 89

1)Push
2)Pop
3)Print
4)Quit
Enter Your Choice : 1

Enter a data : 65

1)Push
2)Pop
3)Print
4)Quit
Enter Your Choice : 3

65 89 45
1)Push
2)Pop
3)Print
4)Quit
Enter Your Choice :2
Popped data= 65
1)Push
2)Pop
3)Print
4)Quit
Enter Your Choice : 2

Popped data= 89
1)Push
2)Pop
3)Print
4)Quit
Enter Your Choice : 2

Popped data= 45
1)Push
2)Pop
3)Print
4)Quit
Enter Your Choice : 2

Stack is empty ....
1)Push
2)Pop
3)Print
4)Quit
Enter Your Choice :4

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
Related Posts Plugin for WordPress, Blogger...
 

Most Reading

Labels