c#中基本链表的实现

1.基本链表的实现

功能:插入,删除,遍历显示

using System;
using System.Collections;
using System.Diagnostics.Eventing.Reader;
using System.Security.Cryptography.X509Certificates;
using System.Text;

public class Node
{
    public Object item;  //数据
    public Node Link;  //指针

    public Node()
    {
        item = "header";  //创建节点s
        Link = null;  

    }

    public Node(Object str)
    {
        item = str;  //使用指定字符构建节点
        Link = null;
    }
}

public class LinkList
{
    public Node header;  //头结点
    public LinkList()
    {//构造函数
        header=new Node();  //构造头结点
    }

    public void Insert(Object str, Object after)
    {//在某一节点后面插入节点
        Node current = Find(after);  //查找某一节点
        if (current == null)
        {
            Console.WriteLine("没有找到前节点无法完成插入操作");
            return;
        }

        Node newnode=new Node(str);
        newnode.Link = current.Link;  //完成插入操作
        current.Link = newnode;

    }

    private Node Find(Object str)
    {//查找某一节点
        Node current = header;
        while(current!= null&¤t.item!=str)
        {//如果当前节点不为空s
            current = current.Link;
        }
        return current;  //返回当前节点
    }

    public void print()  //打印所有节点
    {
        Node current = header.Link;
        while(current != null)
        {
            Console.WriteLine(current.item);
            current = current.Link;
        }
    }

    public Node PreFind(Object str)
    {//查找这个节点的上一个节点
        Node current = header;
        while (current.Link.item != str && current.Link!=null)
        {//如果不为空并且不为这个值
            current = current.Link;
        }
        return current;

    }

    public void Remove(Object str)
    {
        Node current = PreFind(str);  //查找这个节点的前一个节点
        if (current.Link == null)
        {
            Console.WriteLine("没有找到这个要删除的节点");
            return;
        }

        if (current.Link.Link != null)
        {//要删除节点的后面还有节点
            current.Link = current.Link.Link;  //这节连接
        }
        else
        {
            current.Link = null;  //否则直接断开连接
        }
    }

}

public class Test
{
    public static void Main()
    {
        LinkList list=new LinkList();
        list.Insert("jiajia1", "header");
        list.Insert("jiajia2", "jiajia1");
        list.Insert("jiajia3", "jiajia2");
        list.Insert("jiajia4", "jiajia3");
        list.Remove("jiajia4");  //删除节点
        list.print();
    }
}


没有更多推荐了,返回首页