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();
    }
  • 相关阅读:
    第2季:从官方例程深度学习海思SDK及API
    H.264帧结构详解
    Linux内核链表
    在Sqlite中通过Replace来实现插入和更新
    mysql 里随机生成时间
    搭建Cordova + Ionic + WebStorm环境开发Web App应用
    Angular Local Storage 使用方法
    angularJS中controller与directive双向通信
    ui-router传递参数
    Sequelize 和 MySQL 对照
  • 原文地址:https://www.cnblogs.com/Vincent-Bryan/p/5907014.html
Copyright © 2011-2022 走看看