美文网首页
232. Implement Queue using Stack

232. Implement Queue using Stack

作者: a_void | 来源:发表于2016-09-24 18:42 被阅读0次

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();
    }
};

相关文章

网友评论

      本文标题:232. Implement Queue using Stack

      本文链接:https://www.haomeiwen.com/subject/rkixyttx.html