STACK implementation (STRUCTURE & POINTER)
By: Himanshu Tiwari
#include<stdio.h>
#include<stdlib.h>
int x,choice;
struct stack{
int size;
int top;
int *arr;
};
void push(struct stack *ptr,int size){
if(ptr->top>=size-1){
printf("STACK OVERFLOW \n");
}else{
printf("Enter number to be PUSH : ");
scanf("%d",&x);
ptr->top++;
ptr->arr[ptr->top]=x;
printf("Pushed successfully !\n");
}
}
void display(struct stack *ptr){
if(ptr->top==-1){
printf("STACk is empty \n");
}
for(int i=ptr->top; i>=0; i--){
printf("%d\n",ptr->arr[i]);
}
}
void pop(struct stack *ptr){
if(ptr->top==-1){
printf("STACK UNDERFLOW \n");
}else{
printf("popped element : %d\n",ptr->arr[ptr->top]);
ptr->top--;
}
}
int main(){
struct stack *sp=(struct stack *)malloc(sizeof(struct stack));
printf("Enter the size of STACK : ");
scanf("%d",&sp->size);
sp->top=-1;
sp->arr=(int *)malloc(sp->size*sizeof(int));
//stack has been created
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT\n");
do{
printf("enter the choice : ");
scanf("%d",&choice);
switch(choice){
case 1 : push(sp,sp->size);
break;
case 2 :pop(sp);
break;
case 3 : display(sp);
break;
case 4 : printf("EXIT POINT\n");
break;
default : printf("entered wrong choice !\n");
break;
}
}while(choice!=4);
return 0;
}
.png)
Good
ReplyDelete