Quick actions

cmd+k|ctrl+k

Navigation

Languages

Swapping Two stacks

Snippet info

Language

Cpp

Visibility

public

Author

ha7shu

Created

2025-01-23T18:24:18.048357Z

Updated

2025-01-23T18:24:34.104593Z

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

int main(){
    stack<int> st1;
    st1.push(10);
    st1.push(20);
    
    stack<int> st2;
    st2.emplace(49);
    st2.emplace(329);
    
    // before swapping 
    stack<int> temp1 = st1;
    cout << "Stack 1" << endl;
    while(!temp1.empty()){
        cout << temp1.top() << " ";
        temp1.pop();
    }
    cout << endl << "Stack 2" << endl;
    stack<int> temp2 = st2;
    while(!temp2.empty()){
        cout << temp2.top() << " ";
        temp2.pop();
    }
    
    st1.swap(st2);
    
    // after swapping
    cout << endl << "Stack 1" << endl;
    stack<int> swap1 = st1;
    while(!swap1.empty()){
        cout << swap1.top() << " ";
        swap1.pop();
    }
    cout << endl << "Stack 2" << endl;
    stack<int> swap2 = st2;
    while(!swap2.empty()){
        cout << swap2.top() << " ";
        swap2.pop();
    }
    
    return 0;
}
INFO