我试图使用InsertInOrder方法将数字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; }
}
}
}
答案 0 :(得分:2)
您的代码看起来很干净。我不会为你发布一个完整的解决方案,但我会给你一个关于你可以实现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;
}
}
}
}