实现一个类模板

/*此程序实现一个类模板示例*/
#include<iostream>
using namespace std;
template<class T>class List{//链表类模板
struct node{
T data;
node *next;//每个节点有一个地方存放数据,一个指向下一个节点
} *head, *tail;
public:
List(){
head = tail = NULL;
}
void Insert_head(T *item);//向链表首增加数据
void Insert_tail(T *item){//向链表尾增加数据
node* np = new node;
np->data = *item; np->next = NULL;
if (head == tail&&tail == NULL){
head = np; tail = np;
}
else{
tail->next = np; tail = np;
}
}
T Delete(){//从链表首中删除数据
if (head == NULL)//链表为空
exit(0);
node *pn = head;
T teap = head->data;
if (head->next == NULL){//链表只有一个数据的情况
head = NULL;
delete pn;
}
else{
head = head->next;
delete pn;
}
return teap;
}
};
template<class T>void List<T>::Insert_head(T *item){//向链表首增加数据
node *np = new node;
np->data = *item;
np->next = head;
head = np;
if (tail == NULL)
tail = np;
}
///////////////////////////////////////////构造一个person类
class person{
public:
char name[20];
int age;
};
/////////////////////////////////////////主函数
int main(){
int inf;
person ps;
List<int> Link1;
List<person> Link2;//创建两个类
cout << " ----Input 5 person's and int's information --- " << endl;
for (int i = 0; i < 5; i++){
cout << "intput " << i << "inf(name,age)(Link2) (int)(Link1) : ";
cin >> ps.name >> ps.age >> inf;
Link2.Insert_tail(&ps);
Link1.Insert_head(&inf);
}
cout << "-------------The result-------------" << endl;
/////////////////////////////////////////Link2
cout << "Link2(head->tail) : ";
for (int i = 0; i < 4; i++){
ps = Link2.Delete();
cout << ps.name<<" "<<ps.age << " -> ";
}
ps = Link2.Delete();
cout << ps.name << " " << ps.age << endl;
//////////////////////////////////////////Link1
cout << "Link1(head->tail) : ";
for (int i = 0; i < 4; i++){
cout << Link1.Delete() << " -> ";
}
cout << Link1.Delete() << endl;
return 0;
}

原文地址:https://www.cnblogs.com/1996313xjf/p/5810717.html