1、两个栈实现一个队列
思路:
一个栈作为输入栈,一个栈作为输出栈,入队的时候压进输入栈,出队的时候要颠倒一下顺序,因此判断输出栈是否为空,为空的话就先把输入栈的数据弹出压进输出栈,然后从输出栈弹出数据,即为先进先出的顺序。
代码实现:
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里导入数据(导入stIn全部数据)
if (stOut.empty()) {
// 从stIn导入数据直到stIn为空
while(!stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}