Write c program to perform following operations on Dynamic stack 1) Push 2) Pop 3) Display
Dynamic Stack
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
//To create structure stack
struct stack
{
int data;
struct stack *next;
};
typedef struct stack node;
//To define functions
void push(node **, int);
int pop(node **);
int isempty(node *);
void display(node *);
void main()
{
node *top=NULL;
int ch, data;
do
{
printf("\n1.Push \n2.Pop \n3.Display \nOther than above to EXIT.");
printf("\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the data: ");
scanf("%d",&data);
push(&top,data);
break;
case 2:
if(isempty(top))
printf("\nStack is empty.");
else
{
data=pop(&top);
printf("\nRemoved item is: %d",data);
}
break;
case 3:
display(top);
break;
}
}while(ch<=3&&ch>=1);
}
//To add elements in stack
void push(node **top, int data)
{
node *temp=NULL;
temp=(node *)malloc(sizeof(node));
temp->data=data;
temp->next=NULL;
if(*top==NULL)
{
*top=temp;
}
else
{
temp->next=*top;
*top=temp;
}
}
//To check stack is empty or not
int isempty(node *top)
{
if(top==NULL)
return 1;
else
return 0;
}
//To remove elements from stack
int pop(node **top)
{
int data;
node *ptr=NULL;
data=(*top)->data;
ptr=(*top);
*top=ptr->next;
free(ptr);
return data;
}
void display(node *top)
{
node *ptr=NULL;
if(isempty(top))
printf("\nStack is empty");
else
{
printf("\nContent of stack is: ");
ptr=top;
while(ptr!=NULL)
{
printf("%d ",ptr->data);
ptr=ptr->next;
}
}
}
0 Comments