zoukankan      html  css  js  c++  java
  • 单向链表模板

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

    #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();
    }
  • 相关阅读:
    Ubuntu下建立Android开发环境
    c#值类型和引用类型
    Jude Begin
    Eclipse C/C++ development environment creation
    C# var usage from MSDN
    SubSonic应用_Collection
    C#2.0中委托与匿名委托引
    sql语句的执行步骤——zhuan
    图˙谱˙马尔科夫过程·聚类结构 (转载,原始出处不详)
    Hadoop集群新增节点实现方案
  • 原文地址:https://www.cnblogs.com/Vincent-Bryan/p/5907014.html
Copyright © 2011-2022 走看看