数据结构-单链表

什么是单链表?

单链表就像锁链,一环扣一环。每一环我们称为节点多个节点连接起来形成单链。

一个节点有数据域和指针域,如下:

数据域 指针

一个节点可以用指针指向另一个节点,节点与节点间的串连就形成链状的数据存储结构,称为单链表

单链表的特点:

  • 单链表是一种不连续存储的数据结构。
    所谓的不连续是指在计算机物理存储结构中不连续,逻辑结构是连续的。
    数组就是物理结构和逻辑结构都连续的一种结构。因为数组的下标是固定的。
    而单链表的指针可以自由指向,所以在物理结构中单链表的节点呈碎片化存储。

代码如下:

    //链表对象
    public class SingleLinkedList
    {
        private Node head;//链表头部
        private int size;//节点数量

        //链表初始化
        public SingleLinkedList() 
        {
            this.head = new Node();//头节点初始化
            this.size = 0;
        }


        //在链表尾部插入节点
        public bool add(int item) 
        {
            //初始化节点
            Node newNode = new Node(item,null);
            Node tmp = head;
            while (tmp.Next!=null) 
            {
                tmp = tmp.Next;
            }
            tmp.Next = newNode;
            size++;//增加链表数量
            return true;
        }

        //在指定节点位置插入元素
        public bool add(int item, int index)
        {
            //定义插入的节点
            Node newNode = new Node(item, null);
            Node tmp = head;
            //找到插入点节点对象
            for (int i=0;i<index;i++)
            {
                tmp = tmp.Next;
            }
            
            Node node=tmp.Next; //临时存储指定位置后面的节点          
            tmp.Next = newNode; //插入指定位置            
            newNode.Next = node;//插入的新节点连接上后面的位置;

            size++;
            return true;
        }


        //节点删除
        public bool Delete(int index) 
        {
            Node tmp = head;
            for(int i=0;i<index;i++) 
            {
               tmp=head.Next;
            }

            //待删除的节点
            Node current = tmp.Next;
            //待删除节点的后一个节点指向前一个节点
            tmp.Next = current.Next;

            size--;

            Console.WriteLine("删除成功:{0}"+current.Item);
            current = null;

            return true;
        }

        //节点对象
        public class Node
       {
           public  int Item;//数据域
            public Node Next;//下一个节点的对象
            public Node() { }
            public Node(int item,Node next) 
            {
                this.Item = item;
                this.Next = next;
            }
        }

    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容