实现一个类模板

/*此程序实现一个类模板示例*/
#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值