12.Implement Queue using Stacks

https://leetcode.com/problems/implement-queue-using-stacks/

class Queue {
public:
    stack<int> s1;
    stack<int> s2;
    
    // Push element x to the back of queue.
    void push(int x) {
        s1.push(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
        if (s2.empty()){
            adjust();
        }
        int val = s2.top();
        s2.pop();
    }

    // Get the front element.
    int peek(void) {
        if (s2.empty()) {
            adjust();
        }
        return s2.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return s1.empty() && s2.empty();
    }
    
    void adjust() {
        if (s1.empty()) {
            return;
        }
        
        while (!s1.empty()) {
            s2.push(s1.top());
            s1.pop();
        }
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容