C#链表;单向链表

链表操作与算法实现




//节点类

    public class Node
    {
        //数据
        public object Element;
        //指向下一个节点;链接
        public Node Link;
        //构造不带参数Node
        public Node()
        {
            Element = null;
            Link = null;
        }
        //构造带参数的Node
        public Node(object theElement)
        {
            Element = theElement;
            Link = null;
        }
    }
    //链表类LinkedList类
    public class LinkedList
    {
        protected Node header;
        //构造 设置初节点
        public LinkedList()
        {
            header = new Node("header");
        }
        //查找item如果存在就是返回就是和item数据相同的,从header开始查找,如果不存在返回的是null
        public Node Find(object item)
        {
            Node current = new Node();
            current = header;
            while (current.Element != item)
                current = current.Link;
            return current;
        }
        //插入,在给出的after之后插入
        public void Insert(object newitem, object after)
        {
            Node current = new Node();
            Node newNode = new Node(newitem);
            current = Find(after);
            newNode.Link = current.Link;
            current.Link = newNode;
        }
        //查找item如果存在就是返回就是和obj数据相同的的前一个节点(这样就能让链接跳过obj那数据到下一个就相当于删除了),从header开始查找,如果不存在返回的是null
        public Node FindPrevious(object obj)
        {
            Node current = header;
            while (!(current.Link == null) && (current.Link.Element != obj))
                current = current.Link;
            return current;
        }
        //移除obj
        public void Remove(object obj)
        {
            Node p = FindPrevious(obj);
            if (!(p.Link == null))
                p.Link = p.Link.Link;
        }
        //输出链表的元素
        public void PrintList()
        {
            Node current = new Node();
            current = header;
            while (!(current.Link == null))
            {
                Console.WriteLine(current.Link.Element);
                current = current.Link;
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值