数据结构之链表学习笔记

链表的创建,查找,插值与删除
链表的实质在于存储单元之间的联系,一个链表的基本单元包含了存储的数据以及指向下一个单元的指示标,创建好这样的基本单元是创建链表最关键的一步。单链表就如同单行道一样,只能沿着一个方向走下去,这个特点也反映在对链表的操作上面。插值与删除都改变了节点与节点间的联系,注意到这种联系的改变便容易写出链表的操作方法,链表的种类还分为循环链表,双链表,只要理解了链表的构成,操作起来都不会有太大的问题。
下面给出单链表的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:刚开始写博客,链表也很简单其中有什么不对的地方还望各路高手指正批评

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值