首页 > 代码库 > 单向链表模板

单向链表模板

  写个单向链表模板练练手:

#include <bits/stdc++.h>using namespace std;//create // delete // modify // searchclass Node{    public:        int data;        Node* ptr;        Node(int elem= 0, Node* node= NULL){            this->data=http://www.mamicode.com/ elem;             this->ptr= NULL;        }};class MyList{    private:        Node* head;        Node* tail;        int length;    public:        MyList();        ~MyList();        bool append(Node*);        bool insert(int, Node*);        void erase(int);        void print();        int getLength(){return this->length;}};MyList::MyList(){    Node * init = new Node(0,NULL);    this->head = new Node();    this->tail = new Node();    this->head = init;    this->tail = init;    this->length = 0;}MyList::~MyList(){    delete head;    delete tail;}bool MyList::append(Node * n){    this->tail->ptr = n;    this->tail = n;    this->length++;    return true;}bool MyList::insert(int pos, Node* n){    int i = 0;    Node * tmp = new Node();    tmp = this->head;    while(i != pos){        tmp = tmp->ptr;        i++;    }    n->ptr = tmp->ptr;    tmp->ptr = n;    this->length++;    return true;}void MyList::erase(int pos){    int i = 0;    Node * tmp = new Node();    Node * del = new Node();    //del = this->head->ptr;    tmp = this->head->ptr;    while(i != pos - 1){        tmp = tmp->ptr;        i++;    }        del = tmp->ptr;    tmp->ptr = del->ptr;    this->length--;    delete del;}void MyList::print(){    int i = 0;    cout << "len: " <<this->length << endl;    Node * tmp = new Node();    tmp = this->head->ptr;    while(i < this->length){        cout << tmp->data << endl;        tmp = tmp->ptr;        i++;    }    delete tmp;}int main(){    MyList ll;    Node * node2 = new Node(2);    Node * node3 = new Node(3);    Node * node4 = new Node(4);    ll.append(node2);    ll.append(node3);    ll.insert(1,node4);    ll.print();        ll.erase(1);    ll.print();}

 

单向链表模板