欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#数据结构之循环链表的实例代码

程序员文章站 2023-12-05 20:44:34
复制代码 代码如下:    public class node    {   &n...

复制代码 代码如下:

    public class node
    {
        public object element;
        public node link;

        public node()
        {
            element = null;
            link = null;
        }

        public node(object theelement)
        {
            element = theelement;
            link = null;
        }
    }

复制代码 代码如下:

public class linkedlist
    {
        //头结点
        protected node header;

        private int count;

        public linkedlist()
        {
            count = 0;
            header = new node("header");
            header.link = header;
        }

        public bool isempty()
        {
            return (header.link == null);
        }

        public void makeempty()
        {
            header.link = null;
        }

        public void printlist()
        {
            node current = new node();
            current = header;
            while (current.link.element.tostring() != "header")
            {
                console.writeline(current.link.element);
                current = current.link;
            }
        }

        private node findprevious(object n)
        {
            node current = header;
            while (!(current.link == null) && current.link.element != n)
            {
                current = current.link;
            }
            return current;
        }

        private node find(object item)
        {
            node current = new node();
            current = header.link;
            while (current.element != item)
            {
                current = current.link;
            }
            return current;
        }

        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;
            count++;
        }

        public void remove(object n)
        {
            node p = findprevious(n);
            if (!(p.link == null))
            {
                p.link = p.link.link;
                count--;
            }
        }

        public void insertfirst(object n)
        {
            node current = new node(n);
            current.link = header;
            header.link = current;
            count++;
        }

        public node move(int n)
        {
            node current = header.link;
            node tmp;
            for (int i = 0; i <= n; i++)
            {
                current = current.link;
            }
            if (current.element.tostring() == "header")
            {
                current = current.link;
            }
            tmp = current;
            return tmp;
        }

        public node getfirst()
        {
            return header;
        }
    }