特别注意:编写函数前必须先进行模板的声明
#include<iostream>
using namespace std;
template<typename type>
class list;//声明list类
template<typename type>
class listnode
{
friend class list<type>;//访问私有对象,设置为友元函数
public:
listnode():data(type()),next(NULL)
{
}
listnode(type d,listnode<type>*n = NULL):data(d),next(n)
{
}
~listnode()
{
}
private:
type data;
listnode<type>*next;
};
template<typename type>
class list
{
public:
list();
bool pushback(type x);//定义尾插函数
void show()const;//定义显示函数
private:
listnode<type>*first;
listnode<type>*last;
size_t size;
};
template<typename type>
list<type>::list()//初始化链表
{
first = last = (listnode<type>*)malloc(sizeof(listnode<type>));
first->next = last->next = NULL;
size = 0;
}
template<typename type>
bool list<type>::pushback(type x)//尾插函数的实现
{
listnode<type>*s = (listnode<type>*)malloc(sizeof(listnode<type>));
if(s == NULL)
return false;
s->data = x;
s->next = NULL;
last->next = s;
last = s;
size++;
return true;
}
template<typename type>
void list<type>::show()const//显示函数的实现
{
listnode<type>*p = first->next;
while(p != NULL)
{
cout<<p->data<<"-->";
p = p->next;
}
cout<<"null"<<endl;
}
void main()
{
list<int> newlist;//此处int类型可以修改为其他类型
cout<<"输出的链表为:";
for(int i = 97;i<106;++i)
{
newlist.pushback(i);
}
newlist.show();
}