一、题目
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
二、思路
队列中的元素顺序与输入顺序相同,而栈中的元素顺序与输入顺序相反,用两个栈,输入元素的顺序经过两次倒置,可以得到和原顺序相同,及实现了队列,具体在代码中都有注释。
三、代码
class MyQueue {
public:
stack<int> st1; //st1中元素的元素为队列中元素的顺序
stack<int> st2;
MyQueue() {
}
// 将元素 x 推到队列的末尾
void push(int x) { //借助st2暂存原有元素,在st1的元素顺序即为队列中的元素顺序
while(!st1.empty()){ //将st1中原有的元素先移到st2
st2.push(st1.top());
st1.pop();
}
st1.push(x); //新插入的元素总是在st1的栈底
while(!st2.empty()){ //再将st2中的元素移动回st1
st1.push(st2.top());
st2.pop();
}
}
// 从队列的开头移除并返回元素
int pop() {
int tmp = st1.top();
st1.pop();
return tmp;
}
// 返回队列开头的元素
int peek() {
return st1.top(); //st1的栈顶元素即为队列头元素
}
// 如果队列为空,返回 true ;否则,返回 false
bool empty() { //st2只是在插入时暂存元素,其他时候都为空
return st1.empty();
}
};
四、运行结果