点:栈的运用
题意:用两个栈实现一个队列的功能
剑指offer面试题7
思路:栈1用于不断的push入数据,当需要做队列的front、pop时,把栈1的数据全部挨个pop出来并push到栈2,这样数据的顺序,在栈2级实现了逆序,即和队列一致了。数据平时依然push到栈1,需要取时从栈2取,栈2为空了就把栈1再整体pop出来挨个推入栈2。
代码:
#include <stack>
#include <iostream>
template<class T> class STK_Queue {
std::stack<T> stk1;
std::stack<T> stk2;
public:
STK_Queue(){}
~STK_Queue(){}
void push (T val) {
stk1.push(val);
}
bool front (T &val) {
if (stk2.empty()) {
while (!stk1.empty()) {
stk2.push(stk1.top());
stk1.pop();
}
if (!stk2.empty()) {
val = stk2.top();
return true;
} else {
return false;
}
} else {
val = stk2.top();
return true;
}
}
void pop () {
if (stk2.empty()) {
while (!stk1.empty()) {
stk2.push(stk1.top());
stk1.pop();
}
if (!stk2.empty()) {
stk2.pop();
}
} else {
stk2.pop();
}
}
bool empty () {
if (stk1.empty() && stk2.empty()) {
return true;
} else {
return false;
}
}
};
int main () {
STK_Queue<int> stk_q;
for (int i = 0; i < 10; i++) {
stk_q.push(i);
std::cout << "push " << i << "\t";
}
std::cout << std::endl;
while (!stk_q.empty()) {
int s;
stk_q.front(s);
std::cout << "pop " << s << "\t";
stk_q.pop();
}
std::cout << std::endl;
return 0;
}