gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:49 25 4
gpt4 key购买 nike

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

例如我当前的列表 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; }
}
}
}

最佳答案

您的代码看起来很干净。我不会为您发布完整的解决方案,但我会给您一个框架,说明您可以如何实现 InsertInOrder。请注意,有很多方法可以做到这一点。您所要做的就是填写 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;
}
}
}
}

关于c#按顺序插入项目自定义链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26892446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com