请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push
、pop
、peek
、empty
):
实现 MyQueue
类:
void push(int x)
将元素 x 推到队列的末尾int pop()
从队列的开头移除并返回元素int peek()
返回队列开头的元素boolean empty()
如果队列为空,返回true
;否则,返回false
栈的特点:先入后出,队列的特点:先入先出。
这里我们需要使用栈去实现队列,但是栈先进去的在栈底,无法实现队列的pop。
既然一个栈不行,那么两个呢,我们设计一个栈为输入栈,另一个为输出栈。
- 1 输入栈负责接收输入
- 2 接收到pop时,从输出栈输出
- 3 一旦输出栈为空,需要将输入栈中的数据弹栈压入输出栈。
具体代码如下:
class MyQueue {
public:
stack st1;
stack st2;
MyQueue() {
}
void push(int x) {
st1.push(x);
}
void change(){
if (st2.empty()){
while(!st1.empty()){
int x = st1.top(); st1.pop();
st2.push(x);
}
}
}
int pop() {
change();
int y = st2.top(); st2.pop();
return y;
}
int peek() {
change();
int y = st2.top();
return y;
}
bool empty() {
if (st1.empty() && st2.empty()) 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();
*/