c#按顺序插入项目自定义链表

c#按顺序插入项目自定义链表,c#,C#,我正在尝试使用Insertinoder方法将数字8添加到我的列表中 e、 g.我目前的名单5、10、12、14、26、45、52 插入新节点5、8、10、12、14、26、45、52后 我知道我必须遍历列表才能找到正确的位置 但是我从哪里开始呢 class LinkList { private Link list = null; //default value – empty list public void AddItem(int item) //add item to front of

我正在尝试使用Insertinoder方法将数字8添加到我的列表中

e、 g.我目前的名单5、10、12、14、26、45、52

插入新节点5、8、10、12、14、26、45、52后

我知道我必须遍历列表才能找到正确的位置 但是我从哪里开始呢

class LinkList
{

private Link list = null; //default value – empty list

public void AddItem(int item) //add item to front of list
{
    list = new Link(item, list);
}


public void InsertInOrder(int item)
{
    Link temp = list;
    while (temp != null)
    {

        AddItem(item);
        Console.WriteLine(temp.Data);
        temp = temp.Next;

    }
}

public void DisplayItems() // Displays items in list
{
    Link temp = list;
    while (temp != null)
    {
        Console.WriteLine(temp.Data);
        temp = temp.Next;

    }

}
链接类别:

 class Link
    {
        private int data;
        private Link next;

        public Link(int item) //constructor with an item
        {
            data = item;
            next = null;
        }
        public Link(int item, Link list) //constructor with item and list
        {
            data = item;
            next = list;
        }

        public int Data //property for data
        {
            set { this.data = value; }
            get { return this.data; }
        }

        public Link Next //property for next
        {
            set { this.next = value; }
            get { return this.next; }
        }
    }
}

你的代码看起来很干净。我不会为您发布完整的解决方案,但我会为您提供一个框架,说明如何实现
insertinoder
。请注意,有很多方法可以做到这一点。您所要做的就是填写if条件

public void InsertInOrder(int item)
{
    Link temp = list;
    // check to see if the item goes at the front of the list...
    //   hint : there are 2 conditions where it needs to go in the front.
    if (********* || **********)
    {
        list = new Link(item, list);
    }
    else
    {
        while (temp != null)
        {
            // you have to look at the next item and see if it's bigger
            //  which means it goes next.
            //  if there isn't a next item this item belongs next.
            if (*********** || // there is no next item
                ***********) // this item is bigger than the next item
            {
                temp.Next = new Link(item, temp.Next);
                // we are done so set temp to null so we exit the loop
                temp = null;
            }
            else
            {
                // move on to the next item
                temp = temp.Next;
            }
        }
    }
}

做作业?insertinoder while循环应该是开始实现比较的好地方。在插入第一个元素(值1)和最后一个元素(值100)时还要注意边缘情况。这在我的实现中非常有用,非常感谢您的帮助