您的位置:首页 > 其它

List.链表(增删改查)

2013-04-26 22:48 162 查看
typedef int T;

class List{

    struct Node{

        T data;

        Node* next;

        Node(const T& d,Node* next=NULL):data(d),next(next){}

    };

    Node* head;

    int len;

public:

    ~List(){clear();}

    List():head(),len(){}

    int size const{

        return len;

    }

    void travel() const{

        Node* p = head;

        while(p){

            cout << p->data << ' ';

            p = p->next;

        }

        cout  << endl;

    }

    void clear(){

        Node* p = head,*q;

        while(p){

            q = ->next;

    delete p;

            p = q;

        }

        head = NULL,len = 0;

    }

    Node*& getptr(int n){

        if(n<0 || n>len) n=len;

        if(n == 0){

            return head;

        }

        Node* p = head;

        for(int i=1;i<n;i++){

            p = p->next;

        }

        reurn p->next;

    }

    void insert(const T& d,int n){

        Node*& p=getptr(n);

        Node* q = new Node(d,p);

        p = q;

        ++len;

    }

    void erase(int n){

        Node*& p = getptr(n);

        if(p){

            Node* q = p;

            p = p->next;

    delete q;

    --len;

        }

    }

    void remove(const T& d){

Node*& p = find(d);

if(p){

    Node* q = p;

    p = p->next;

    delete q;

      --len;

}

    }

    Node*& find(const T& d){

if(len==0 || head->data==d)

    return head;

Node* p = head;

while(p->next && p->next->data!=d)

    p = p->next;

return p->next;

    }

    void update(const T& oldv,const T& newv){

Node* p = find(oldv);

if(p){

    p->data = newv;

}

    }

    //对 [ ] 的重载

    T& operator[](int index) throw(const char*){

if(index<0 || index>=len) throw "x";

return getptr(index)->data;

    }

};

PS:一个班里的舍友回学校了,孤身一人在帝都,加油!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 List