手动实现一个自动排序的双向链表

双向链表

 public class DoubleLinkedList
    {
        private Node head;
        public void add(int data)
        {
            if (head==null)
            {
                head = new Node(data);
            }
            else
            {
                head = head.ADD(new Node(data));
            }
        }
        public override string ToString()
        {
            if (head ==null)
            {
                return string.Empty;
            }
            else
            {
                return this.head.ToString();
            }
        }
        public class Node
        {
            private int data;
            private Node next;
            private Node prev;
            public int Data 
            {
                get { return this.data; }
            }
            public Node(int data) 
            {
                this.data = data;
            }
            public Node ADD(Node newnode)
            {
                if (data>newnode.data)   //传入值大于当前值
                {
                    newnode.next = this;
                    if (this.prev!=null)
                    {
                        this.prev.next = newnode;
                        newnode.prev = this.prev;
                    }
                    this.prev = newnode;
                    return newnode;
                }
                else
                {
                    if (this.next!=null)
                    {
                        this.next.ADD(newnode);
                    }
                    else
                    {
                        this.next = newnode;
                        newnode.prev = this;
                    }
                    return this;
                }
            }
            public override string ToString()
            {
                string str = data.ToString();
                if (next!=null)
                {
                    str += "" + next.ToString();
                }
                return str;
            }
        }
    }

 

posted @ 2021-08-13 15:42  raccon2001  阅读(36)  评论(0)    收藏  举报