//使用模板类实现通用链表
#include <iostream>
using namespace std;
template<typename Type>//知识点2.1 类模板的前向声明
class List;
template<typename Type>
class ListNode
{
friend class List<Type>;//知识点2.1
public:
ListNode()
:data(Type()),next(NULL)//知识点1 根据Type类型,自动生成对应的初始化0值。
{
}
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 push_back(Type x);
void show_list()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>));
last->next = NULL;
size = 0;
}
template<typename Type>
bool List<Type>::push_back(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_list()const
{
ListNode<Type> *p = first->next;
while(p != NULL)
{
cout<<p->data<<"-->";
p =p->next;
}
cout <<"Nul."<<endl;
}
int main()
{
/* //知识点1
int a = 0;
C++里全是对象,哪怕是基本类型,也是类对象,下面两种方式相当于调用了整形类型类的构造函数
int a = int();
int a(0);
cout<< a<<endl;*/
List<int> mylist;
for(int i = 1;i<=10;++i)
{
mylist.push_back(i);
}
mylist.show_list();
return 0;
}