zoukankan      html  css  js  c++  java
  • 实现一个类模板

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

  • 相关阅读:
    PLSQL WEBSERVICES 发布
    WebService开发指南
    来自10位成功IT人士的23条经验教训
    图片格式区别:png8,png24,jpg,jpeg,gif,webp
    当你在工作中失去动力时该怎么办?
    面向对象的反思
    关于前端面试的一些心得
    有什么好的交友软件吗?求推荐
    区块链开发的11种顶级编程语言
    CSRF的几种防御方法的利弊分析
  • 原文地址:https://www.cnblogs.com/1996313xjf/p/5810717.html
Copyright © 2011-2022 走看看