两个栈实现双端队列
2014-09-21 22:47
204 查看
一个笔试题,当时竟然没想出来,现在实现下
/* 用两个栈实现双端队列 栈s1,s2。 pushback()和popback(),必须在s2为空的情况,把s2的都放s1中 pushfront()和popfront(),必须是在s1为空,把s1的都给放到s2中 */ #include <iostream> #include <stack> using namespace std; template <typename T> class DequeBy2Stack { private: int maxsize; stack<T> s1; stack<T> s2; public: DequeBy2Stack(int size):maxsize(size){} void pushback(T n); T popback(); void pushfront(T n); T popfront(); int size(); bool empty(); }; template <typename T> bool DequeBy2Stack<T>::empty() { return s2.empty()&&s1.empty(); } template <typename T> int DequeBy2Stack<T>::size() { return s1.size()+s2.size(); } template <typename T> void DequeBy2Stack<T>::pushback(T n) { if(this->size()==maxsize) { throw new std::exception("Invalid push"); } while(!s2.empty()) //必须将s2中的数据都导入到s1中 { int tmp=s2.top(); s1.push(tmp); s2.pop(); } s1.push(n); } template <typename T> T DequeBy2Stack<T>::popback() { while(!s2.empty()) { int tmp=s2.top(); s1.push(tmp); s2.pop(); } if(!s1.empty()) { int tmp=s1.top(); s1.pop(); return tmp; } else { throw new exception("Invalid popback()"); } } template <typename T> void DequeBy2Stack<T>::pushfront(T n) { if(this->size()==maxsize) { throw new std::exception("Invalid push"); } while(!s1.empty()) { int tmp=s1.top(); s2.push(tmp); s1.pop(); } s2.push(n); } template <typename T> T DequeBy2Stack<T>::popfront() { while(!s1.empty()) { int tmp=s1.top(); s2.push(tmp); s1.pop(); } if(!s2.empty()) { int tmp=s2.top(); s2.pop(); return tmp; } else { throw new exception("Invalid popfront"); } } int main() { DequeBy2Stack<int> test(8); int n; for(int i=1;i<=8;i++) { test.pushback(i); } test.popback(); test.popfront(); test.popfront(); test.popfront(); test.pushfront(100); test.pushfront(101); test.pushback(30); test.pushfront(102); test.popfront(); while(!test.empty()) cout<<test.popback()<<endl; system("pause"); }
相关文章推荐
- java数据结构之LinkedDeque(用链表实现的双端(即头尾两个哨兵节点)双向(node里两个指向)队列)
- [疯狂Java]集合:Deque(双端队列)以及两个实现(ArrayDeque、LinkedList)、Stack(摒弃)、各线性表性能分析
- 用两个栈实现一个队列 (CLRS 10.1-6)
- 程序员面试题精选(48):两个堆栈模拟队列c++代码实现
- 2.用两个顺序存储结构的栈实现一个队列
- 用两个栈实现队列
- 两个栈实现一个队列
- 实现了两个普通的队列,一个优先权队列
- 解题笔记(12)——用两个栈实现队列
- 用两个栈实现队列
- sicily 1889解题报告(bfs维护两个队列,实现最短路径)
- 算法导论10.1-7习题解答(用两个队列实现一个栈)
- 用两个栈实现一个队列的功能
- 用两个堆栈实现一个队列
- 程序员面试题精选100题(18)-用两个栈实现队列
- 两个栈实现队列的功能
- 程序员面试题精选(18):用两个栈实现队列
- 用两个栈实现一个队列的功能
- 【题目5】如何使用两个栈来实现一个队列
- 两个栈实现一个队列