//*************************单链表(2个类)**********************************
using namespace std;
template<typename T>class LinkList;
template<typename T>
class Node //结点类
{
public:
Node():next(NULL){}
private:
T data;
Node<T> *next;
friend class LinkList<T>;
};template<typename T>
class LinkList //链表类
{
public:
LinkList()
{
phead = new Node<T>;
}
~LinkList()
{
Node<T> *tmp;
while(phead != NULL)
{tmp = phead->next;
free(phead);
phead = tmp;
}
}
void InsertHead(const T &value) // 头插法
{
Node<T> *p = new Node<T>;
p->data = value;
p->next = phead->next;
phead->next = p;
}
void DeleteHead() //头删法
{
Node<T> *tmp = phead->next;
phead->next = tmp->next;
free(tmp);
}
void Show() //打印单链表里面的值
{
Node<T> *p= phead->next;
while(p != NULL)
{
cout<<p->data<<" ";
p = p->next;
}
}
private:
Node<T> *phead; //头结点
};
int main()
{
LinkList<int> LinkList;
LinkList.InsertHead(1);
LinkList.InsertHead(2);
LinkList.InsertHead(3);
LinkList.Show();
return 0;
}
//***********************************************************
//*************************** 嵌套类***********************
#include<iostream>
using namespace std;
template<typename T>
class LinkList{
public:
LinkList()
{
phead = new Node;
}
~LinkList()
{
Node *tmp;
while(phead != NULL)
{
tmp = phead->next;
free(phead);
phead = tmp;
}
}
void InsertHead(const T &value)
{
Node *p = new Node;
p->data = value;
p->next = phead->next;
phead->next = p;
}
void DeleteHead()
{
Node *tmp = phead->next;
phead->next = tmp->next;
free(tmp);
}
void Show()
{
Node *p= phead->next;
while(p != NULL)
{
cout<<p->data<<" ";
p = p->next;
}
}
private:
class Node
{public:
Node():next(NULL){}
T data;
Node *next;
};
Node *phead;};
int main()
{
//LinkList<int> LinkList;
//LinkList.InsertHead(1);
//LinkList.InsertHead(2);
//LinkList.InsertHead(3);
//LinkList.Show();
LinkList<float> tmp;
tmp.InsertHead(1.21);
tmp.InsertHead(2.22);
tmp.InsertHead(3.14592);
tmp.Show();
return 0;
}