您的位置:首页 > 其它

模板栈的实现

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.
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: