看了下C++ primer中的类模板后顺手写的。。
(未实现复制构造) 功能少,可能还会有错误,哈哈。
代码:
#include <iostream>
template<class type>
class Data
{
public:
type data;
Data *next;
};
template<class type>
class stack
{
public:
stack():sz(0),head(NULL) {}
stack(type x):sz(0),head(NULL) {push(x);}
stack(int n,type x);
type size() {return sz;}
type is_empty() {return sz==0;}
void push(type a);
void pop();
type& top();
void list_all();
void destroy();
~stack() {destroy();}
private:
Data<type> *head;
unsigned int sz;
};
template<class type>type& stack<type>::top()
{
if(!is_empty())
return head->data ;
std::cout<<"空栈"<<std::endl;
exit(1);
}
template<class type>void stack<type>::list_all()
{
Data<type> *p=this->head;
while(p)
{
std::cout<<p->data << " ";
p=p->next ;
}
std::cout<<std::endl;
}
template<class type>std::ostream& operator<<(std::ostream& out,stack<type>& t)
{
out<<t.top();
return out;
}
template<class type>stack<type>::stack(int n,type x):sz(0),head(NULL)
{
for(int i=0;i<n;++i) push(x);
}
template<class type>void stack<type>::push(type a)
{
Data<type> *p=new Data<type>;
p->data =a;
p->next =NULL;
if(is_empty())
head=p;
else
{
p->next =head;
head=p;
}
++sz;
}
template<class type>void stack<type>::pop()
{
if(!is_empty())
{
Data<type> *p=head;
head=head->next ;
delete p;
--sz;
std::cout<<"data left:"<<size()<<std::endl;
}
else
{
std::cout<<"空栈"<<std::endl;
}
}
template<class type>void stack<type>::destroy()
{
while(!is_empty()) pop();
}
void test()
{
stack<double >a;
for(int i=0;i<5;++i)
a.push (i*0.1);
a.list_all();
while(!a.is_empty ())
{
std::cout<<a<<std::endl;
a.pop();
}
}
int main()
{
test();
}
运行截图: