Delete middle element of a stack | C ++ code to delete middle of a stack without using additional data structure . ; Deletes middle of stack of size n . Curr is current item number ; If stack is empty or all items are traversed ; Remove current item ; Remove other items ; Put all items back except middle ; Driver function to test above functions ; push elements into the stack ; Printing stack after deletion of middle .
#include <bits/stdc++.h> NEW_LINE using namespace std ; void deleteMid ( stack < char > & st , int n , int curr = 0 ) { if ( st . empty ( ) curr == n ) return ; char x = st . top ( ) ; st . pop ( ) ; deleteMid ( st , n , curr + 1 ) ; if ( curr != n / 2 ) st . push ( x ) ; } int main ( ) { stack < char > st ; st . push ( '1' ) ; st . push ( '2' ) ; st . push ( '3' ) ; st . push ( '4' ) ; st . push ( '5' ) ; st . push ( '6' ) ; st . push ( '7' ) ; deleteMid ( st , st . size ( ) ) ; while ( ! st . empty ( ) ) { char p = st . top ( ) ; st . pop ( ) ; cout << p << " ▁ " ; } return 0 ; }