题目链接:https://leetcode.cn/problems/implement-queue-using-stacks/
栈的特点是先进后出,而队列的特点是先进先出,我们用两个栈正好能把顺序反过来实现类似队列的操作。
stackData 作为压入栈,向队尾添加的所有新元素只往 stackData 中压入;
stackTemp 作为临时栈,只有求队首元素和删除队首元素时才会用到 stackTemp 来颠倒元素顺序。
向队尾添加元素:
删除队首元素:
求队首元素:
C++代码如下:
class MyQueue {
public:
stack<int> stackData, stackTemp;
MyQueue() {
}
void push(int x) {
stackData.push(x);
}
int pop() {
while (!stackData.empty()) {
stackTemp.push(stackData.top());
stackData.pop();
}
int res = stackTemp.top();
stackTemp.pop();
while (!stackTemp.empty()) {
stackData.push(stackTemp.top());
stackTemp.pop();
}
return res;
}
int peek() {
while (!stackData.empty()) {
stackTemp.push(stackData.top());
stackData.pop();
}
int res = stackTemp.top();
while (!stackTemp.empty()) {
stackData.push(stackTemp.top());
stackTemp.pop();
}
return res;
}
bool empty() {
return stackData.empty();
}
};
/**
* 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();
*/