# 225.Implement Stack Using Queues

**225.Implement Stack Using Queues**

难度:Easy

> 使用队列实现栈的下列操作：

```
push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque（双端队列）来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的（例如, 对一个空的栈不会调用 pop 或者 top 操作）。
```

由于队列是FIFO，栈是LIFO，所以需要两个队列来实现栈的功能:

```
class MyStack {
private:
    queue<int> a;
    queue<int> b;
public:
    /** Initialize your data structure here. */
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        if(a.empty())
        {
            b.push(x);
        }
        else
        {
            a.push(x);
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int tmp;
        if(a.empty())
        {
            tmp=b.back();
            int s=b.size();
            while(s-- >1)
            {
                a.push(b.front());
                b.pop();
            }
            b.pop();
        }
        else
        {
            tmp=a.back();
            int s=a.size();
            while(s-->1)
            {
                b.push(a.front());
                a.pop();
            }
            a.pop();
        }
        //cout<<a.size()<< "+"<<b.size()<<endl;
        
        return tmp;
    }
    
    /** Get the top element. */
    int top() {
        if(a.empty())
            return b.back();
            
        else
            return a.back();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return a.empty() && b.empty() ;
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */
```

运行结果：

> 成功 执行用时 : 8 ms, 在Implement Stack using Queues的C++提交中击败了96.69% 的用户 内存消耗 : 8.9 MB, 在Implement Stack using Queues的C++提交中击败了34.06% 的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/225.implement_stack_using_queues.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
