since Stack is LIFO, Queue is FIFO;
in order to implement LIFO, need to have a stack1 to buff the data and back to stack2 for pop. it is just like cooling the hot water with 2 cups, it can reverse the order.
But one thing need to notice. we only reverse the order if we have no water in stack2 for drink. so only in pushing, we directly pour water in stack1. Other cases, we need to check if stack2 is empty so as to reverse hot water in stack1 to 2.
It save time.
#include
#include
using namespace std;
template
class MyQueue{
public:
MyQueue(){
}
~MyQueue(){
}
void push(T val){
sin.push(val); //for push, we don't care about sout
}
void pop(){
move(sin, sout); // for the rest, only move sin to sout
sout.pop(); // iff sout is empty
}
T front(){
move(sin, sout);
return sout.top();
}
T back(){
move(sout, sin);
return sin.top();
}
int size(){
return sin.size()+sout.size();
}
bool empty(){
return sin.empty()&&sout.empty();
}
void move(stack
&src, stack
&dst){ if(dst.empty()){ while(!src.empty()){ dst.push(src.top()); src.pop(); } } } private: stack
sin, sout; }; int main(){ MyQueue
q; for(int i=0; i<10; ++i){ q.push(i); } cout<
<<" "<
<
Output:
Executing the program....
$demo
0 9
1 10
10 0