模板栈的实现
2015-11-01 22:59
239 查看
此方法通过指针方式插入对象,释放时调用对象delete。
#include<fstream> #include<iostream> #include<string> using namespace std; template<class T> class Stack { private: struct Link { T* data; Link* next; Link(T* da,Link* ne):data(da),next(ne){} }* head; public: Stack():head(NULL){} ~Stack() { while(head) { delete pop(); //释放data数据; } } void push(T* da) { Link* he = new Link(da,head); head = he; } T* peek() { return head ? head->data : 0; } T* pop() { if(head == NULL) return 0; T* da = head->data; Link* he = head; head = head->next; delete he; return da; } }; class X { public: virtual ~X(){} //用于调用子类对象的析构 }; int main(int argc, char* argc[]) { if(argc == 1)return 0; ifstream in(argv[1]); //主函数参数列表 Stack<string> textlines; string line; while(getline(in, line)) { textlines.push(new string(line)); } string* s; for(int i = 0; i < 10; ++i) { if((s = textlines.pop()) == 0) break; cout << *s <<endl; delete s; } Stack<X> xx; for(int j = 0; j < 10; ++j) { xx.push(new X); //new X() is also ok. } }
相关文章推荐
- 由WEBX5自动生成的代码对JS中prototype的研究
- linux RHEL6 中md0重启后变为 md127的解决办法
- 正确的慢跑姿势是怎样的?
- SpringMVC拦截器(资源和权限管理)
- 曝光补偿
- 控制器之间的传值—— segue与代理的合作
- 顺便再写一个递归 复习一下前面学的知识
- Sudoku - The 2015 China Collegiate Programming Contest && UESTC 1222
- java Servlet接口及应用
- hdu5119 DP
- 深入分析js中的constructor 和prototype
- Miscalculation(模拟题)
- 25 1000-digit Fibonacci number - Project Euler
- 备份恢复八大核心
- 通过NSNotification来监听键盘弹出和弹回
- RAID学习笔记
- linux中缺少某些命令该怎么办呢?------以tree命令为例
- 试用了下ITIL开源管理工具iTop,感觉很爽,准备尽快部署并首先实现公司CMDB治理
- Eclipse – SimpleTagSupport was not found on the Java Build Path
- Makefile 自动生成依赖