目录
1.题目描述
2.思路
思路是很清晰的,栈是先进后出,而队列是先进先出,所以要用栈实现队列,就必须用到两个栈,一个输入栈,一个输出栈
在push数据的时候,只要数据放进输入栈就好,「但在pop的时候,操作就复杂一些,输出栈如果为空,就把进栈数据全部导入进来(注意是全部导入)」,再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据就可以了。
如果进栈和出栈都为空的话,说明模拟的队列为空了。
3.代码展示
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stIn.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
//只有当stOut为空的时候,再从stIn里导入数据(导入strIn全部数据)
if (stOut.empty()) {
//从stIn导入数据直到stIn为空,即全部导入
while (!stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
/** Get the front element. */
int peek() {
int res = this->pop();//直接使用已有的pop函数
stOut.push(res);//因为pop函数弹出了元素res,所以再添加回去
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return stIn.empty() && stOut.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();
*/
其实思路还是好理解的,实现起来也不复杂,建议以后大家写文章粘贴代码的时候附上运行的截图,这样大家看起来方便,也有助于自己回顾。
4.用队列实现栈
4.1题目描述
4.2思路
前面已经介绍了栈和队列两者的特性了,用栈实现队列就很简单了,相反的,用队列也能实现栈,也是需要两个队列,还是一个输入队列一个输出队列吗?
当然不是这样的,队列是先进先出的规则,把一个队列中的数据导入另一个队列中,数据的顺序并没有变,并有变成先进后出的顺序。
所以用栈实现队列, 和用队列实现栈的思路还是不一样的,这取决于这两个数据结构的性质。
但是依然还是要用两个队列来模拟栈,只不过没有输入和输出的关系,而是另一个队列完全是用来备份的!
4.3代码实现
class MyStack {
public:
queue<int> que1;
queue<int> que2;//辅助队列,用来备份的
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int size = que1.size();
size--;
while (size--) {//将que1导入que2,但留下最后一个元素
que2.push(que1.front());
que1.pop();
}
int result = que1.front();//留下最后一个元素就是要返回的值
que1.pop();
que1 = que2;//再将que2赋值给que1;
while (!que2.empty()) {//清空que2
que2.pop();
}
return result;
}
/** Get the top element. */
int top() {
return que1.back();
}
/** Returns whether the stack is empty. */
bool empty() {
return que1.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();
*/