码迷,mamicode.com
首页 > 其他好文 > 详细

单向链表模板

时间:2016-09-25 22:22:41      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

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

#include <bits/stdc++.h>
using namespace std;

//create 
// delete 
// modify 
// search
class Node{
    public:
        int data;
        Node* ptr;
        Node(int elem= 0, Node* node= NULL){
            this->data= 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();
}

 

单向链表模板

标签:

原文地址:http://www.cnblogs.com/Vincent-Bryan/p/5907014.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!