[LeetCode]94. 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 toppeek/pop from topsize, 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).

 

Subscribe to see which companies asked this question

 
解法1:使用两个栈s1和s2。进队列调用s1.push();因为队列的先进先出特性,出队列不能直接在s1上操作,我们用辅助栈s2来操作:如果s2非空,则直接s2.pop(),否则先将s1中的所有元素倒腾到s2中,再调用s2.pop();同理对于取队列头元素也是相同做法;判断是否为空则只要判断s1和s2是否都是空的就可以了。注意题目限制了假设所有的操作都是有效的,所以在pop()和peek()两个操作上不需要做额外的非空判断。
class Queue {
public:
    // 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() && !s1.empty()) {
            while (!s1.empty()) {
                s2.push(s1.top());
                s1.pop();
            }
        }
        s2.pop();
    }
    // Get the front element.
    int peek(void) {
        if (s2.empty() && !s1.empty()) {
            while (!s1.empty()) {
                s2.push(s1.top());
                s1.pop();
            }            
        }
        return s2.top();
    }
    // Return whether the queue is empty.
    bool empty(void) {
        return s1.empty() && s2.empty();
    }
private:
    std::stack<int> s1, s2;
};

 

解法2:使用一个栈s即可解决。在进行push()操作的时候,如果s中有元素,则将它们搬到辅助栈tmp中,然后再将x push到s中;接下来又将tmp中的所有元素搬回s中。这样最先进入的元素就在栈顶了。

class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) {
        std::stack<int> tmp;
        while (!s.empty()) {
            tmp.push(s.top());
            s.pop();
        }
        s.push(x);
        while (!tmp.empty()) {
            s.push(tmp.top());
            tmp.pop();
        }
    }
    // Removes the element from in front of queue.
    void pop(void) {
        s.pop();
    }
    // Get the front element.
    int peek(void) {
        return s.top();
    }
    // Return whether the queue is empty.
    bool empty(void) {
        return s.empty();
    }
private:
    std::stack<int> s;
};

实际上这种方法还是使用到了一个辅助栈,并且在入栈操作上需要循环多次,所以效率更低,但是空间复杂度不见得下降了。

posted @ 2015-11-19 10:31  AprilCheny  阅读(143)  评论(0编辑  收藏  举报