单链表模板


#include 

using namespace std;

template
struct Node{
    Type data;
    Node *next;
    Node(Node *ptr = nullptr):next(ptr){}
    Node(const Type &val,Node *ptr = nullptr):data(val),next(ptr){}
};


template
class List{
    Node *head,*tail;
    int len;
public:
    List(){
        head = new Node;
        tail = head;
        len = 0;
    }
    List(const List &src){
        head = new Node;
        tail = head;
        len = 0;///要先初始化本身,不然会赋值失败,clear的问题
        *this = src;
    }
    ~List(){
        clear();
        delete head;
        tail = head = nullptr;
    }


    List & operator=(const List &src){
        clear();
        Node *p = src.head->next;
        while(p){
            (*this).push_back(p->data);
            p = p->next;
        }
        return *this;
    }


    void push_front(const Type &val){
        head->next = new Node(val,head->next);
        if(!len) tail = head->next;
        len++;
    }
    void push_back(const Type &val){
        tail = tail->next = new Node(val);
        len++;
    }
    void insert(int pos,const Type &val){
        assert(pos>=0 && pos *p = findPtr(pos-1);
        p->next = new Node(val,p->next);
        len++;
    }


    void clear(){
        Node *p = head->next;
        while(p){
            Node *ptmp = p;
            p = p->next;
            delete ptmp;
        }
        head->next = nullptr;
        tail = head;
        len = 0;
    }
    void erase(int pos){
        assert(pos>=0 && pos *p;
        if(pos == 0) p = head;
        else p = findPtr(pos - 1);
        Node *ptmp = p->next;
        p->next = p->next->next;
        delete ptmp;
        if(pos == len - 1) tail = p;
        len--;
    }
    void pop_front(){erase(0);}
    void pop_back(){erase(len-1);}


    void replace(int pos,const Type &val){
        assert(pos>=0&&pos *p = findPtr(pos);
        p->data = val;
    }


    Node *findPtr(int pos)const{
        if(pos<-1 && pos>=len) return nullptr;
        Node *p = head;
        int i = -1;
        while(inext;
            i++;
        }
        return p;
    }


    int find(const Type &val)const{
        Node *p = head->next;
        int j = 0;
        while(p && p->data != val) {
            p = p->next;
            j++;
        }
        return j *p = head->next;
        int j = 0;
        while(p && !cmp(p->data,val)) {
            p = p->next;
            j++;
        }
        return j &src){
        clear();
        for(int i = 0;i &src){
        clear();
        for(int i = 0;i *p = head->next;
        while(p){
            cout<data<<(p->next?"->":"");
            p = p->next;
        }
        cout< v;
    for(int i = 0;i<10;i++) v.push_back(i);

    List l;
    l.createList_back(v);
    l.write();

    l.pop_back();
    l.write();

    l.pop_front();
    l.write();

    l.erase(4);
    l.write();

    l.insert(2,100);
    l.write();

    cout< lc = l;
    lc.write();
    cout<