数据结构之链表学习笔记

来源:互联网 发布:可以在家干的工作 知乎 编辑:程序博客网 时间:2024/06/06 13:10

链表的创建,查找,插值与删除
链表的实质在于存储单元之间的联系,一个链表的基本单元包含了存储的数据以及指向下一个单元的指示标,创建好这样的基本单元是创建链表最关键的一步。单链表就如同单行道一样,只能沿着一个方向走下去,这个特点也反映在对链表的操作上面。插值与删除都改变了节点与节点间的联系,注意到这种联系的改变便容易写出链表的操作方法,链表的种类还分为循环链表,双链表,只要理解了链表的构成,操作起来都不会有太大的问题。
下面给出单链表的C++代码:

#include<iostream>using namespace std;class Node{    public:        int data;        Node* next;        node(){        next = NULL;        }};class LinkList{    public:        LinkList(){            head = NULL;    }        //insert part        void insert(Node* node,int index){            if(head==NULL){return;}            if(index==0)            {                node->next=head;                head=node;                return;            }        //search for the position inserted            Node* current_node=head;            int count = 0;         while(current_node->next!=NULL&&count<index-1)         {             current_node = current_node->next;             count++;         }         if(count==index-1)         {             node->next=current_node->next;             current_node->next = node;         }    }        void delete_node(int index){        if(head==NULL){return;}        Node* current_node=head;        int count=0;        if(index==0)        {            current_node=head->next;            head = current_node;            delete current_node;            return;        }        while(current_node->next!=NULL&&count<index-1)        {            current_node = current_node->next;            count++;        }        if(count==index-1)        {            Node* delete_node=current_node->next;            current_node->next=delete_node->next;            delete delete_node;        }       }    void output(int index){        if(head==NULL){ return; }        if(index==0){ cout<<head->data<<endl; return;}        Node* current_node = head->next;        int count=1;        while(current_node!=NULL&&count<index)        {            current_node=current_node->next;            count++;        }        cout<<current_node->data<<endl;    }};

PS:刚开始写博客,链表也很简单其中有什么不对的地方还望各路高手指正批评

0 0
原创粉丝点击