模板的使用

#include <iostream>
using namespace std;

template <typename T,typename H>
class List{
public:
    void Add(T a,H b);
    List();
    void Delete(T a);
    void Loop();
protected:
    struct Node{
        T x;
        H y;
        Node *next;
    };
    Node *head;
};

template <typename T,typename H>

List<T,H>::List(){
}

template <typename T,typename H>
void List<T,H>::Add(T a,H b){
    Node *p = new Node;
    p->next = NULL;
    p->x = a;
    p->y = b;
    p->next = head;
    head = p;
}

template <typename T,typename H>
void List<T,H>::Delete(T a){
     Node *tmp = head;
     Node *pp = new Node;
     pp->next = head;
     while(tmp->next!=NULL){
         if(tmp->x==a){
             pp->next = tmp->next;
             break;
         }
         pp = pp->next;
         tmp = tmp->next;
     }
}

template <typename T,typename H>
void List<T,H>::Loop(){
    Node *tmp = head;
    do{
        cout<<tmp->x<<" "<<tmp->y<<endl;
        tmp = tmp->next;
    }while(tmp->next!=NULL);
}

int main(){
    List<int,int> ll;
    ll.Add(3,4);
    ll.Add(4,5);
    ll.Add(6,7);
    cout<<"before delete"<<endl;
    ll.Loop();
    ll.Delete(4);
    ll.Delete(3);
    cout<<"after delete"<<endl;
    ll.Loop();
    return 0;
}

你可能感兴趣的:(模板的使用)