基本思路:
1、创建2个栈
stackIn : 放入元素
stackOut: 弹出元素
2、put 方法
直接 push到statckIn 栈就可
3、弹出元素
因为队列的特点是 先进先出的, 而栈是先进后出的,所以栈先进 的元素 被压在了栈低。 所以我们需要先把 栈的元素 弹出放入 另一个stackOut栈中,这样 顺序就会反转,然后 按顺序 一直弹出 stackOut的元素即可。直到stackOut元素被 弹空,然后 再从stackIn中 弹出元素 放到stackOut栈中, 然后 再弹出……
代码如下:
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stIn.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
if (stOut.empty()) {
// 从stIn导入数据直到stIn为空
while(!stIn.empty()) {
//先top()取出 stIn的元素,然后 再pop出栈
stOut.push(stIn.top());
stIn.pop();
}
}
//先top取出stout的元素,然后 再pot出栈
int result = stOut.top();
stOut.pop();
return result;
}
/** Get the front element. */
int peek() {
int res = this->pop(); // 直接使用已有的pop函数
stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return stIn.empty() && stOut.empty();
}
};