解题思路
之前写两个栈实现一个队列:一个栈用于模拟队列添加元素,另一个栈用于模拟队列删除元素或者获取队头元素。这其实就是根据两个数据结构的差异来实现对应的功能
然后写这个队列模拟栈。首先我是这样想的:假如有一个栈 1-2-3 ,队列只需将元素一次push就行 1-2-3
如果你需要获取栈顶元素 3,那么就对应队列获取队尾,队列的特性是先进先出,即先出1再2再3,。然后我这里想的是用队列的size()操作。
采用一个count记录队列元素个数以及一个临时队列temp,将count>1时队列进行出列pop到temp.这个过程如下:
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int count = q1.size();
if(count == 1)
{
int tmp = q1.front();
q1.pop();
return tmp;
}
queue<int> temp;
while(count > 1)//当队列元素>1,将q1前count-1个元素暂存到temp
{
int tmp = q1.front() ;
temp.push(tmp);
q1.pop();
count--;
}
int tmp = q1.front();
q1.pop(); //将队尾的元素(对应栈顶元素,此时在队首位置)出列。
while(!temp.empty()) //将temp中的元素放回到q1
{
q1.push(temp.front());
temp.pop();
}
return tmp;
}
/** Get the top element. */
int top() {
return q1.back(); //返回队尾元素,对应栈顶元素
}
/** Returns whether the stack is empty. */
bool empty() {
return q1.empty();
}
private:
queue<int> q1;
};