# LeetCode (232)：用栈实现队列

LeetCode 相关的文章：

#### 题目描述

class MyQueue {

public:

/** Initialize your data structure here. */

MyQueue() {

}

/** Push element x to the back of queue. */

void push(int x) {

}

/** Removes the element from in front of queue and returns that element. */

int pop() {

}

/** Get the front element. */

int peek() {

}

/** Returns whether the queue is empty. */

bool empty() {

}

};

/**

* Your MyQueue object will be instantiated and called as such:

* MyQueue* obj = new MyQueue();

* obj->push(x);

* int param_2 = obj->pop();

* int param_3 = obj->peek();

* bool param_4 = obj->empty();

*/

push 完成入队

pop 完成出队

，peek

用来获取队首的元素

empty 用来判断队列是否为空

#### 问题分析

in 栈负责元素的“入队”，out 栈负责元素的“出队”。

#### 代码实现

class MyQueue {

stack<int> in;

stack<int> out;

public:

/** Initialize your data structure here. */

MyQueue() {

}

/** Push element x to the back of queue. */

void push(int x) {

in.push(x);

}

/** Removes the element from in front of queue and returns that element. */

int pop() {

int x = 0;

if (out.empty()) {

while (!in.empty()) {

x = in.top();

out.push(x);

in.pop();

}

}

x = out.top();

out.pop();

return x;

}

/** Get the front element. */

int peek() {

int x = 0;

if (out.empty()) {

while (!in.empty()) {

x = in.top();

out.push(x);

in.pop();

}

}

return out.top();

}

/** Returns whether the queue is empty. */

bool empty() {

if (in.empty() && out.empty()) {

return true;

}

return false;

}

};

/**

* Your MyQueue object will be instantiated and called as such:

* MyQueue* obj = new MyQueue();

* obj->push(x);

* int param_2 = obj->pop();

* int param_3 = obj->peek();

* bool param_4 = obj->empty();

*/

#### 提交结果

”，然后观察
“输出” 和 “预期结果”

” 按钮。点击 “提交” 按钮后，系统会使用更多的测试用例来测试我们写的函数体，

。我们以上代码 “提交” 以后的截图如下：