7. 用两个栈实现队列
2015-08-20 16:26
323 查看
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。解析
两个栈stack1 和stack2入队列:直接压入stack1即可
出队列:如果stack2不为空,把stack2中的栈顶元素直接弹出;否则,把stack1的所有元素全部弹出压入stack2中,再弹出stack2的栈顶元素
实现
#include <iostream> #include <stack> using namespace std; template<typename T> class MyQueue{ public: MyQueue(); ~MyQueue(); void addTail(const T& val); //在队列末尾添加元素 T deleteHead(); //删除队首元素 private: stack<T> stack1; stack<T> stack2; }; template<typename T> MyQueue<T>::MyQueue(){ } template<typename T> MyQueue<T>::~MyQueue(){ } template<typename T> void MyQueue<T>::addTail(const T& val){ stack1.push(val); } template<typename T> T MyQueue<T>::deleteHead(){ if(stack2.empty()){ if(stack1.empty()){ throw new exception("队列是空的"); }else{ while(stack1.empty() == false){ stack2.push(stack1.top()); stack1.pop(); } } } T head = stack2.top(); stack2.pop(); return head; } void Test(char actual, char expected) { if(actual == expected) printf("Test passed.\n"); else printf("Test failed.\n"); } int main() { MyQueue<char> queue; queue.addTail('a'); queue.addTail('b'); queue.addTail('c'); char head = queue.deleteHead(); Test(head, 'a'); head = queue.deleteHead(); Test(head, 'b'); queue.addTail('d'); head = queue.deleteHead(); Test(head, 'c'); queue.addTail('e'); head = queue.deleteHead(); Test(head, 'd'); head = queue.deleteHead(); Test(head, 'e'); system("pause"); return 0; }
相关文章推荐
- 3.一些小tips
- android判断网络是否可用
- Java中的序列化
- eclipse 远程 debug
- DOM(一)-12-(document获取节点byName)
- 性能优化:使用SparseArray代替HashMap<Integer,Object>
- VS2005调试技巧集合
- (10)Xamarin.Android - 储存数据于Windows Azure
- 问题:C# List;结果:C#中数组、ArrayList和List三者的区别
- 性能优化:使用SparseArray代替HashMap<Integer,Object>
- JQuery HTML之捕获、设置、元素添加、元素删除
- 设计模式实例(Lua)笔记之五(Bridge模式)
- java返回间隔时间(时分秒)
- main中int argc, char **argv 含义
- STL:类模板
- android 点滴——XML
- POJ 3633
- DOM(一)-11-(document获取节点byId)
- (9)Xamarin测试账号申请与续用
- (8) Xamarin使用Jar檔