一、题目描述
你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty)。
二、思路
栈是先进后出,队列是先进先出。只要用两个栈来回倒数据就可以实现队列的要求了。 队列的push操作是没有什么问题的,但是pop操作,就得注意了,如果有两个栈,stack1、stack2,stack1代表进栈,stack2代表出栈,队列的Pop操作首先要判断stack2是否为空,如果为空的话,则把stack1中的放到stack2中,然后从Stack2中pop一个出来就好了。
代码如下:
class MyQueue {
public:
stack<int> stack1;
stack<int> stack2;
/** Initialize your data structure here. */
MyQueue() {
}
/** 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() {
int val;
if(!stack2.empty()){
val = stack2.top();
stack2.pop();
}
else{
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
val = stack2.top();
stack2.pop();
}
return val;
}
/** Get the front element. */
int peek() {
int val;
if(!stack2.empty())
val = stack2.top();
else{
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
val = stack2.top();
}
return val;
}
/** Returns whether the queue is empty. */
bool empty() {
if(stack1.empty()&&stack2.empty())
return true;
else
return false;
}
};
三、分析
这题的核心操作,就是把stack1中的值放入到stack2中,然后在出栈。那可以在这里就写一个函数,专门是用来把stack中的值放入到stack2中的值。