用两个栈实现队列
2011-02-19 10:36
337 查看
题目是就用两个栈来实现队列....
思路还是比较清晰的,所以直接上代码.......
思路还是比较清晰的,所以直接上代码.......
//用两个栈实现队列 #include<iostream> #include<stack> using namespace std; template <typename T> class MyQueue{ public: MyQueue(){}; T pop(); void push(T); bool empty(); private: stack<T> stack1; //用于入队和入队 stack<T> stack2; //用于出队 }; template<typename T> T MyQueue<T>::pop(){ //出队 T temp; if(!stack2.empty()){temp=stack2.top();stack2.pop();} else{ if(stack1.empty()) {cout<<"error"<<endl;return 0;} else{ while(!stack1.empty()){ stack2.push(stack1.top()); stack1.pop(); } temp=stack2.top(); stack2.pop(); } } return temp; } template<typename T> void MyQueue<T>::push(T t){ //入队 stack1.push(t); return; } template<typename T> bool MyQueue<T>::empty(){ /*if(stack1.empty()&&stack2.empty()) return true; else return false;*/ return stack1.empty()&&stack2.empty()?true:false; } void test(MyQueue<int> q){ //测试 int data[]={1,2,3,4,5,6,7,8,9,10}; for(int i=0;i<=6;i++) q.push(data[i]); for(int i=0;i<=5;i++) cout<<q.pop()<<" "; cout<<endl; for(int i=7;i<=9;i++) q.push(data[i]); while(!q.empty()){ cout<<q.pop()<<" "; } cout<<endl; return; } int main(void){ MyQueue<int> q; test(q); system("pause"); return 0; }
相关文章推荐
- [算法学习]两个栈实现一个队列
- 用两个栈区实现一个队列
- 两个栈实现队列的功能
- 两个队列实现栈
- 用两个栈实现一个队列
- 用两个堆栈来实现队列
- 用两个栈实现一个队列
- 面试题7:用两个栈实现一个队列
- 剑指offer:用两个栈实现队列、用两个队列实现一个栈(java)
- 用两个栈来实现一个队列,完成队列的Push和Pop操作。队列中的元素为int类
- 两个栈实现一个队列
- 【5】用两个栈实现队列
- 用两个栈如何实现队列?
- 剑指offer 用两个栈实现队列 @python
- 用两个栈实现队列
- 两个栈实现一个队列
- 剑指offer-两个栈实现队列
- 微软100题(57)两个栈实现队列
- 用两个栈实现一个队列
- 用两个栈实现一个队列