两个队列实现一个栈
2016-01-02 20:48
302 查看
两个队列("先进先出")实现一个栈("后进先出")
//.h
本文出自 “花开彼岸” 博客,请务必保留此出处http://zxtong.blog.51cto.com/10697148/1730929
//.h
#include<iostream> using namespace std; #include <queue> #include<string> template<class T> class Stack { public: Stack() :_size(0) {} ~Stack() {} void Push(T t); void Pop(); T Top(); int Size(); protected: queue<T> A; queue<T> B; int _size; }; template<class T> void Stack<T>::Push(T t) { A.push(t); ++_size; } template<class T> void Stack<T>::Pop() { while(A.size()>1) { B.push(A.front()); A.pop(); } A.pop(); while(B.size()!=0) { A.push(B.front()); B.pop(); } --_size; } template<class T> T Stack<T>::Top() { while(A.size()>1) { B.push(A.front()); A.pop(); } T tmp=A.front(); B.push(A.front()); A.pop(); while(B.size()!=0) { A.push(B.front()); B.pop(); } return tmp; } template<class T> int Stack<T>::Size() { return _size; }//.c
#include"StackQueue.h" #include<iostream> using namespace std; #include<string> void Test1() { Stack<int> s; s.Push(1); s.Push(2); s.Push(3); while(s.Size()) { cout<<s.Top()<<" "; s.Pop(); } cout<<endl; } void Test2() { Stack<string> s; s.Push("ld"); s.Push("wor"); s.Push(" "); s.Push("llo"); s.Push("he"); while(s.Size()) { cout<<s.Top(); s.Pop(); } cout<<endl; } int main() { Test1(); // Test2(); return 0; }
本文出自 “花开彼岸” 博客,请务必保留此出处http://zxtong.blog.51cto.com/10697148/1730929
相关文章推荐
- OC(构造函数,分类等知识总结)
- android studio2.0解决办法 Plugin is too old, please update to a more recent version
- 实现客户端和服务器双向的防重放攻击
- 备忘
- 线段树模板
- 使用讯飞语音实现语音识别,朗读文字
- Java Web 跨平台 - 使用Apache Axis2引擎发布基于Java语言的WebService并跨平台调用实例
- Burp Suite抓包、截包和改包
- python基础-面向对象
- 关于margin-top失效的解决办法
- Hibernate中常见问题 No row with the given identifier exists问题的原因及解决
- 使用存储过程查询并按每页10条记录分页显示图书借阅纪录
- 编译安装httpd-2.4
- 对Xcode菜单选项的详细探索(来自董铂然的微博http://www.cnblogs.com/dsxniubility/p/4983614.html)
- 关于padding
- 哈夫曼树及哈夫曼编码 C++
- Html知识点
- N皇后问题
- hadoop-1.2.1 Eclipse plugin
- linux下makefile配置文件及make工具的使用