232. Implement Queue using Stacks

Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.

Notes:

  • You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

Solution:

class Queue {
public:
    // Push element x to the back of queue.
    stack<int> s;
    bool cp = true;
    
    void reverse(stack<int>& ss){
        stack<int> t;
        while(!ss.empty()){
            t.push(ss.top());
            ss.pop();
        }
        ss = t;
    }
    
    void push(int x) {
        if(cp) s.push(x);
        else{
            reverse(s);
            s.push(x);
            cp = true;
        }
    }

    // Removes the element from in front of queue.
    void pop(void) {
        if(cp){
            reverse(s);
            s.pop();
            cp = false;
        }else{
            s.pop();
        }
    }

    // Get the front element.
    int peek(void) {
        if(cp){
            cp = false;
            reverse(s);
            return s.top();
        }else{
            return s.top();
        }
    }

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

推荐阅读更多精彩内容