思路一:deque
class MyStack {
public:
deque<int> q;
MyStack() {
}
void push(int x) {
q.push_back(x);
}
int pop() {
int back = q.back();
q.pop_back();
return back;
}
int top() {
return q.back();
}
bool empty() {
return q.empty();
}
};
思路二:两个队列
具体思路:
q1为栈(为之前入队的栈的存储),q2作辅助作用(入q2前q2为空)
x入栈:x入队q2,将q1中所有元素出队,入队q2,保证了x在栈顶,将q1和q2交换(不是赋值)
出栈:从q1出队
栈顶:q1的队头
判断为空:q1是否为空
class MyStack {
public:
queue<int> q1, q2;
MyStack() {
}
void push(int x) {
q2.push(x);
while (!q1.empty()) {
int frt = q1.front();
q1.pop();
q2.push(frt);
}
swap(q1, q2); //交换
}
int pop() {
int frt = q1.front();
q1.pop();
return frt;
}
int top() {
return q1.front();
}
bool empty() {
return q1.empty();
}
};
易错点:swap(q1, q2)而不是赋值
思路三:一个队列
实现细节:变量n记录之前入栈的元素
x入栈:将x入队,然后将之前的n的元素依次出队入队
class MyStack {
public:
queue<int> q;
int n = 0;
MyStack() {
}
void push(int x) {
q.push(x);
for (int i = 0; i < n; ++i) {
q.push(q.front());
q.pop();
}
n++;
}
int pop() {
int frt = q.front();
q.pop();
return frt;
}
int top() {
return q.front();
}
bool empty() {
return q.empty();
}
};