コード ランダム レコーディング アルゴリズム トレーニング キャンプ 10 日目| 232. スタックを使用してキューを実現する| 225. キューを使用してスタックを実現する|


この種の問題解決は依然として間違っています。大工場を恥じる必要はありません。

232. スタックを使用したキューの実装

class MyQueue {
    
    
    stack<int>sta1;
    stack<int>sta2;
public:
    MyQueue() {
    
    

    }
    
    void push(int x) {
    
    
        sta1.push(x);
    }
    
    int pop() {
    
    
    //这里注意,在sta2为空的时候再操作
        if(sta2.empty()){
    
    
        while(!sta1.empty()){
    
    
            sta2.push(sta1.top());
            sta1.pop();
        }
        }

        int a=sta2.top();
        sta2.pop();
        return a;

    }
    
    int peek() {
    
    
        int a=this->pop();
        //把弹出来的元素放入sta2里面
        sta2.push(a);
        return a;
        }
    
    bool empty() {
    
    
        if(sta1.empty()&&sta2.empty())return true;
        else return false;
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

225. キューを使用したスタックの実装

class MyStack {
    
    
    queue<int>que1;
    queue<int>que2;

public:
    MyStack() {
    
    

    }
    
    void push(int x) {
    
    
        que1.push(x);
    }
    
    int pop() {
    
    
            int size=que1.size();
        while(size!=1){
    
    
            size--;
            que2.push(que1.front());
            que1.pop();
        }
        int res=que1.front();
        que1.pop();
        que1=que2;
        while(!que2.empty()){
    
    
            que2.pop();
        }
        return res;
    }
    
    int top() {
    
    
        return que1.back();
    }
    
    bool empty() {
    
    
        return que1.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */

おすすめ

転載: blog.csdn.net/weixin_43541510/article/details/132112223