题目链接:https://leetcode.cn/problems/implement-stack-using-queues/
1.用两个队列实现栈
C++代码如下:
class MyStack {
public:
queue<int> dataQue; // 数据队列,该队列存储元素的顺序就是对应的栈存储元素的顺序
queue<int> tempQue; // 临时队列,利用该队列实现dataQue中元素与新元素的次序调换
MyStack() {
}
void push(int x) {
tempQue.push(x);
while (!dataQue.empty()) {
tempQue.push(dataQue.front());
dataQue.pop();
}
swap(dataQue, tempQue);
}
int pop() {
int res = dataQue.front();
dataQue.pop();
return res;
}
int top() {
return dataQue.front();
}
bool empty() {
return dataQue.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
2.用一个队列实现栈
class MyStack {
public:
queue<int> dataQue; // 数据队列,该队列存储元素的顺序就是对应的栈存储元素的顺序
MyStack() {
}
void push(int x) {
int n = dataQue.size();
dataQue.push(x);
while (n--) {
dataQue.push(dataQue.front());
dataQue.pop();
}
}
int pop() {
int res = dataQue.front();
dataQue.pop();
return res;
}
int top() {
return dataQue.front();
}
bool empty() {
return dataQue.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/