两个队列实现一个栈

 

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

class MyStack {
private:
    queue<int> que1;
    queue<int> que2; 
public:
    MyStack() {
    }
    void Push(int x) {
        que1.push(x);
    }
    int Pop() {
        int size = que1.size();
        size--;
        while (size--) { 
            que2.push(que1.front());
            que1.pop();
        }

        int result = que1.front(); 
        que1.pop();
        que1 = que2; 
        while(!que2.empty()) { 
            que2.pop();
        }
        return result;
    }

    int Size(){
        return que1.size();
    }

    int Top() {
        return que1.back();
    }

    bool Empty() {
        return que1.empty();
    }
};

int main(){
    MyStack sta;
    sta.Push(1);
    sta.Push(2);
    sta.Push(3);
    cout <<"size:" << sta.Size() << endl;
    cout <<"Pop:" << sta.Pop() << endl;
    cout <<"size:" << sta.Size() << endl;
    return 0;
}
/*
输出结果:
size:3
Pop:3
size:2
*/

 

posted @ 2020-09-15 18:05  西瓜不懂柠檬的酸  Views(126)  Comments(0Edit  收藏  举报
levels of contents