前言
用两个栈实现队列
一、两个栈模拟队列的入队操作
代码如下(示例):
void push(int x) {
stack1.push(x);
}
二、两个栈模拟队列的出队操作
代码如下(示例):
int pop() {
if (stack2.empty() == true){
while (stack1.empty() == false){
stack2.push(stack1.top());
stack1.pop();
}
}
if (stack2.empty() == true) return -1;
else {
int temp = stack2.top();
stack2.pop();
return temp;
}
}
注释:维护两个栈,第一个栈(stack1)支持插入操作,第二个栈(stack2)支持删除操作。栈的特点是先入后出,而队列的特点是先入先出。在加入元素时,放在第一个栈,然后再将他们一个个弹栈放到第二栈,这样第二栈的弹栈(删除操作)顺序就是刚刚这些元素的入栈顺序,正好符合队列的先入先出的特点,所以在模拟队列的出队操作时,先判断第二个栈(stack2)是否为空,若为空,则将第一个栈的元素一个个弹出放到第二个栈,若不为空,则直接弹出栈顶的元素。
三、完整代码
代码如下(示例):
class MyQueue {
public:
stack<int> stack1,stack2;
/** Initialize your data structure here. */
MyQueue() {
while (stack1.empty() == false) stack1.pop();
while (stack2.empty() == false) stack2.pop();
}
/** Push element x to the back of queue. */
void push(int x) {
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if (stack2.empty() == true){
while (stack1.empty() == false){
stack2.push(stack1.top());
stack1.pop();
}
}
if (stack2.empty() == true) return -1;
else {
int temp = stack2.top();
stack2.pop();
return temp;
}
}
/** Get the front element. */
int peek() {
if (stack2.empty() == true){
while (stack1.empty() == false){
stack2.push(stack1.top());
stack1.pop();
}
}
if (stack2.empty() == true) return -1;
else {
return stack2.top();
}
}
/** Returns whether the queue is empty. */
bool empty() {
if (stack2.empty() == true && stack1.empty() == true) return true;
else 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();
*/