链栈模板


#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 ListStack{
    Node *head;
    int len;
public:
    ListStack(){
        head = new Node;
        len = 0;
    }
    ListStack(const ListStack &src){
        head = new Node;
        len = 0;///要先初始化本身,不然会赋值失败,clear的问题
        *this = src;
    }
    ~ListStack(){
        clear();
        delete head;
        head = nullptr;
    }


    ListStack & operator=(const ListStack &src){
        clear();
        Node *p = src.head->next,*q = head;
        while(p){
            q = q->next = new Node(p->data);
            p = p->next;
        }
        len = src.len;
        return *this;
    }


    void push(const Type &val){
        head->next = new Node(val,head->next);
        len++;
    }

    void clear(){
        Node *p = head->next;
        while(p){
            Node *ptmp = p;
            p = p->next;
            delete ptmp;
        }
        head->next = nullptr;
        len = 0;
    }
    void pop(){
        assert(len>0);
        Node *p = head;
        Node *ptmp = p->next;
        p->next = p->next->next;
        delete ptmp;
        len--;
    }

    Type & top(){
        assert(len>0);
        return head->next->data;
    }
    const Type & top()const{
        assert(len>0);
        return head->next->data;
    }


    int size()const{return len;}
    bool empty()const{return !len;}


    void create(const vector &src){
        clear();
        for(int i = 0;i";
        Node *p = head->next;
        while(p){
            cout<data<<(p->next?"->":"");
            p = p->next;
        }
        if(head->next) cout<<"-->";
        cout<<"base";
        cout< v;
    for(int i = 0;i<10;i++) v.push_back(i);

    ListStack ls;
    ls.create(v);
    ls.write();

    ls.pop();
    ls.write();

    cout< lsc = ls;
    cout<