Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,923 questions

51,856 answers

573 users

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

1 Answer

0 votes
#include <iostream>
#include <stack> 

void deleteMiddleElement(std::stack<char> &st, int size, int current = 0) { 
    if (st.empty() || current == size) { 
        return; 
    }
    
    char el = st.top(); 
    st.pop();
    
    deleteMiddleElement(st, size, current + 1); 
    
    if (current != size / 2) { 
        st.push(el); 
    }
}

int main() { 
    std::stack<char> st; 
    
    st.push('3'); 
    st.push('5'); 
    st.push('1'); 
    st.push('m'); 
    st.push('9'); 
    st.push('2'); 
    st.push('7'); 
    
    deleteMiddleElement(st, st.size()); 
    
    while (!st.empty()) { 
        char el = st.top(); 
        st.pop(); 
        std::cout << el << " "; 
    } 
}




/*
run:

7 2 9 1 5 3 

*/

 



answered May 24, 2023 by avibootz
edited May 24, 2023 by avibootz
...