两个栈实现一个队列——C++ 利用STL 栈stack实现
2014-06-17 22:09
405 查看
思路如下:
利用STL stack类构造栈s1,s2.
入队时,将元素压入s1。出队时,判断s2是否为空,如不为空,则直接弹出栈顶元素;如为空,则将s1的元素逐个“倒入”s2把最后一个元素弹出并出队
#include<iostream> #include<stack> using namespace std; template <class T>//类模板 class myqueue { public: stack<T> s1; stack<T> s2; //判断队列是否为空 int IsEmpty(){ return s1.empty()==1&&s2.empty()==1; } //返回队列大小 int GetSize() { return (s1.size()+s2.size()); } //入队操作 void EnQueue(T a){ s1.push(a); } //返回队头元素 T GetFront() { if(!s2.empty()) return(s2.top()); else { if(s1.empty()){ cout<<"队列为空"<<endl; exit(0); } while(!s1.empty()){ s2.push(s1.top()); s1.pop(); } return(s2.top()); if(s1.empty()){ cout<<"队列为空"<<endl; exit(0); } } } //出队操作 void DeQueue(){ if(!s2.empty()) s2.pop(); else{ if(s1.empty()){ cout<<"队列为空"<<endl; exit(0); } while(!s1.empty()){ s2.push(s1.top()); s1.pop(); } s2.pop(); if(s1.empty()){ cout<<"队列为空"<<endl; exit(0); } } } }; int main() { myqueue<int> a; for(int i=0;i<5;++i){ a.EnQueue(i); } for(int i=0;i<5;++i){ cout<<a.GetFront()<<" "; a.DeQueue(); } return 0; }
相关文章推荐
- 利用两个栈实现一个队列(C++版)
- 利用两个队列实现一个栈(C++版)
- 用两个栈实现一个队列,用两个队列实现一个栈,C++ STL版
- C++利用模板实现一个队列
- C++ 用两个栈实现一个队列
- C++面试题:两个队列实现一个栈
- 《剑指Offer》附加题_用两个队列实现一个栈_C++版
- 两个堆栈实现一个队列 , 利用两个队列实现一个堆栈(Java)
- C++:利用两个队列实现栈的操作
- C++之用两个栈实现一个队列
- 利用两个队列实现一个栈
- C/C++之用两个栈实现一个队列的功能
- 用两个栈实现一个队列的功能,请用C++实现它
- 【C++】两个栈实现一个队列
- 两个栈模拟一个队列和两个队列模拟一个栈(c++实现)
- C++:利用两个栈实现队列操作
- 两个栈来实现一个队列的C++代码
- 【C++】两个队列实现一个栈
- C++两个队列实现一个栈
- 程序员面试宝典之数据结构基础----C++两个栈实现一个队列功能