Delete the middle element of a stack in C++

In this tutorial, we will learn how to delete the middle element of a stack in C++. We can use the STL (Standard template library) stack and have to delete the middle element. This can be done by using other data structures also. Below, given is a simple and interesting solution.

For example:

Input  : Stack[] = [12, 24, 3, 48, 5]
Output : Stack[] = [12, 24, 48, 5]

Input  : Stack[] = [10, 23, 33, 54, 5, 76]
Output : Stack[] = [10, 23, 54, 5, 76]

How to Delete the middle element of a stack in C++

We first remove all the elements one by one and identify the middle element. Then, in our recursive calls, we push back all the elements except the middle one.

Here, is a dry run for the approach:

How to Delete the middle element of a stack in C++

Here, is the code implementation:

#include<bits/stdc++.h> 
using namespace std; 

void deletemid(stack<int> &st, int n, 
            int curr=0) 
{ 

if (st.empty() || curr == n) 
  return; 
 
int x = st.top(); 
st.pop(); 

deletemid(st, n, curr+1); 

// Put all items back except middle 
if (curr != n/2) 
  st.push(x); 
} 


int main() 
{ 
  stack<int> st; 

  
  st.push(10); 
  st.push(23); 
  st.push(33); 
  st.push(54); 
  st.push(5); 
  st.push(76);  

  deletemid(st, st.size()); 


  while (!st.empty()) 
  { 
    int p=st.top(); 
    st.pop(); 
    cout << p << " "; 
  } 
  return 0; 
} 

Output:

76 5 54 23 10

You may also interested in reading the below tutorials”

Count the number of occurrences of an element in a linked list in C++

Constructors in C++

Exception handling in C++

Thank you! Please comment for suggestions.

Leave a Reply

Your email address will not be published. Required fields are marked *