主要思路就是将先入队的元素转变为后入队,队头为栈顶,队尾为栈底。
方法一:使用两个队列q1,q2,先将元素入队到q2,然后将q1的元素插入到q2中,最后q1与q2互换,q1队头为栈顶,队尾为栈底。
方法二:使用一个队列,先将元素插入到队列中,然后将原来的元素重新插入到队列中,达到后进的元素始终在队头的效果。
/*入栈时,首先将元素入队到q2,然后将q1的全部元素出队到q2
最后互换q1,q2; q1的前端和后端分别对应栈顶和栈底
队列是先进先出,栈是先进后出
所以我们主要就是将先入队的元素借助辅助队列,变化为后入队的元素
始终满足队头元素是最后入栈的
*/
//两个队列
class MyStack1 {
private:
queue<int> q1;
queue<int> q2;
public:
MyStack() {
}
void push(int x) {
q2.push(x);//先插到队列2中
while(!q1.empty()) {//将队列1中的元素插入到队列2中
q2.push(q1.front());
q1.pop();
}
//swap(q1,q2);
while(!q2.empty()) {
q1.push(q2.front());
q2.pop();
}
}
int pop() {
int x = q1.front();
q1.pop();
return x;
}
int top() {
return q1.front();
}
bool empty() {
return q1.empty();
}
};
//一个队列
class MyStack {
private:
queue<int> q;
public:
MyStack() {
}
void push(int x) {
int n = q.size();
q.push(x);
for(int i = 0;i<n;i++) {//让当前插入元素前面的元素都跑到他后面,达到后进先出的目的
q.push(q.front());
q.pop();
}
}
int pop() {
int x = q.front();
q.pop();
return x;
}
int top() {
return q.front();
}
bool empty() {
return q.empty();
}
};