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,990 questions

51,935 answers

573 users

How to remove all even elements from a stack in C++

1 Answer

0 votes
#include <iostream>       
#include <stack> 
           
using namespace std; 
    
static void removeEvenElements(stack<int> &st) { 
    stack<int> tmp; 
    
    while (!st.empty()) { 
        int val = st.top(); 
        
        if (val % 2 == 1) 
            tmp.push(val); 
            
        st.pop(); 
    }

    while (!tmp.empty()) { 
        st.push(tmp.top()); 
        tmp.pop(); 
    } 
} 
    
void printStack(stack<int> st) {
  while (!st.empty()) {
     cout << st.top() << ' ';
     st.pop();
  }
}
 
int main ()
{
    stack<int> st;
 
    for (int i = 0; i < 10; i++) 
        st.push(i);
 
    printStack(st);
     
    removeEvenElements(st);
 
    cout << endl;
     
    printStack(st);
 
    return 0;
}     
       
       
       
/*
run:

9 8 7 6 5 4 3 2 1 0 
9 7 5 3 1 
    
*/

 



answered Apr 8, 2020 by avibootz

Related questions

1 answer 179 views
1 answer 59 views
1 answer 181 views
1 answer 144 views
1 answer 175 views
1 answer 126 views
...