用2个stack模拟一个queue
#include <iostream> #include <stack> using namespace std; class MyQueue{ public: void push(int value); void pop(); int front(); int back(); bool empty(); private: stack<int> stackPush; stack<int> stackPop; }; void MyQueue::push(int value) { stackPush.push(value); } void MyQueue::pop() { if (stackPop.empty()) while(!stackPush.empty()){ stackPop.push(stackPush.top()); stackPush.pop(); } if (!stackPop.empty()) stackPop.pop(); else cout<<"Queue already empty!"<<endl; } int MyQueue::front() { if (stackPop.empty()) while(!stackPush.empty()){ stackPop.push(stackPush.top()); stackPush.pop(); } if (!stackPop.empty()) return stackPop.top(); else { cout<<"Queue already emtpy!"<<endl; return -1; } } int MyQueue::back() { if (!stackPush.empty()) return stackPush.top(); else if (stackPush.empty() && !stackPop.empty()){ stack<int> stackTmp; while (!stackPop.empty()){ stackTmp.push(stackPop.top()); stackPop.pop(); } int returnValue = stackTmp.top(); while (!stackTmp.empty()){ stackPop.push(stackTmp.top()); stackTmp.pop(); } return returnValue; } else if (stackPush.empty() && stackPop.empty()){ cout<<"queue already empty!"<<endl; return -1; } } bool MyQueue::empty() { if (stackPush.empty() && stackPop.empty()) return true; return false; } int main() { MyQueue myQueue; for (int i = 0; i < 10; i++) { int value = rand()%100; cout<<"EnQueuing element : "<<value<<endl; myQueue.push(value); cout<<"Current Front Element : "<<myQueue.front()<<" Current Back Element : "<<myQueue.back()<<endl<<endl; } cout<<"Push over!"<<endl; while (!myQueue.empty()) { cout<<"DeQueuing element : "<<myQueue.front()<<endl; myQueue.pop(); } return 0; }
EOF