LeetCode – Implement Stack using Queues

题目:

Implement the following operations of a stack using queues.

  • push(x) — Push element x onto stack.
  • pop() — Removes the element on top of the stack.
  • top() — Get the top element.
  • empty() — Return whether the stack is empty.

Example:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);  
stack.top();   // returns 2
stack.pop();   // returns 2
stack.empty(); // returns false

Notes:

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

解题:

本地使用queue实现一个stack的功能, queue特点是先进先出, stack的特点是先进后出

  1. 调整push部分:每加入新元素x时,把queue中现存的元素从队列头(front)元素取出放入放入队列(队列的rear),这样pop和top时顺序与stack一致,先进后出, 其他三个操作也就直接调用queue的操作即可,参见代码如下:                  

实现:

class MyStack {
private:
    queue<int> q;
        
public:
    /** Initialize your data structure here. */
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
        for (int i=0; i<q.size()-1;i++){
            q.push(q.front());
            q.pop();
        }
                
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int x = q.front();
        q.pop();
        return x;
    }
    
    /** Get the top element. */
    int top() {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
};

解题:

        本地使用queue实现一个stack的功能, queue特点是先进先出, stack的特点是先进后出

  1. 调整pop或top部分: 把queue中现存的元素从队列头(front)元素取出放入放入队列(队列的rear),循环size-1次, top操作获取后恢复原有顺序, pop操作直接出队列, push操作也就直接调用queue的操作即可,参见代码如下:

class MyStack {
private:
    queue<int> q ;
        
public:
    /** Initialize your data structure here. */
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);              
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int x;
        for (int i=0; i<q.size()-1;i++){
            q.push(q.front());
            q.pop();
        }
        x = q.front();
        q.pop();
        return x;
    }
    
    /** Get the top element. */
    int top() {
        int x;
        for (int i=0; i<q.size()-1;i++){
            q.push(q.front());
            q.pop();
        }
        x = q.front();
        
        q.push(q.front());
        q.pop();
        return x;
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
};

Be First to Comment

发表回复