该题算是比较简单的,思路是定义两个栈,一个做为入栈,一个做为出栈。入队列的话直接将元素压入入栈,出队列的话首先判断出栈是否为空,为空则将入栈中的元素依次压入出栈中,再从出栈弹出元素。
class Queue { public: // Push element x to the back of queue. void push(int x) { instack.push(x); } // Removes the element from in front of queue. void pop(void) { if(!outstack.empty()){ outstack.pop(); return; } if(!instack.empty()){ while(!instack.empty()){ outstack.push(instack.top()); instack.pop(); } outstack.pop(); } } // Get the front element. int peek(void) { if(!outstack.empty()){ return outstack.top(); } if(!instack.empty()){ while(!instack.empty()){ outstack.push(instack.top()); instack.pop(); } return outstack.top(); } } // Return whether the queue is empty. bool empty(void) { return !instack.empty() || !outstack.empty() ? false : true; } private:
//辅助栈 stack<int> instack, outstack; };
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/ny_mg/article/details/46848399