Are you facing deleting elements on Stack? This tutorial will help you to delete any element from Stack. Here I am using the C program to solve this program. Let’s jump into our coding part.
C program to delete any element from the Stack
#include<stdio.h>
#define size 50
int stack[size];
int top=-1;
void push(int data){
if(top>=size){
printf("Stack OverFlow");
}else{
top=top+1;
stack[top]=data;
}
}
int pop(){
if(top<=-1){
printf("Stack Underflow");
}else{
int deleteItem=stack[top];
top--;
return deleteItem;
}
}
void display(){
printf("The Stack is: \n");
for(int i=0; i<=top; i++){
printf(" %d ", stack[i]);
}
printf("\n");
}
int main(){
int array[50];
int num, index;
printf("How many data you want to stored:");
scanf("%d", &num);
for(int i=0; i<num; i++){
int x;
printf("Enter your Data:");
scanf("%d", &x);
push(x);
}
display();
printf("Enter the index number you want to delete:");
scanf("%d", &index);
int totalDeleteItem=top;
for(int i=top; i>=index; i--){
array[i]=pop();
}
for(int i=index+1; i<=totalDeleteItem; i++){
push(array[i]);
}
display();
}
Output
