所以我学校给我布置了一个作业,要在排序列表中添加一个数字,而不仅仅是一个列表-IntNode列表,如果我做对了,那就是一个链接列表(也许我错了,我不知道这是什么东西)用英语称呼)。无论如何,我非常非常不擅长。因此,如果有人可以查看我的代码并告诉我我的错误在哪里,我将不胜感激。现在,它返回-1,我要疯了!所以这是代码:
public class IntNode
{
private int value;
private IntNode next;
// constructors
public IntNode(int value)
{
this.value = value;
this.next = null;
}
public IntNode(int value, IntNode next)
{
this.value = value;
this.next = next;
}
//getters
public int GetValue()
{
return this.value;
}
public IntNode GetNext()
{
return this.next;
}
// setters
public void SetValue(int value)
{
this.value = value;
}
public void SetNext(IntNode next)
{
this.next = next;
}
public bool HasNext()
{
return this.next != null;
}
public override string ToString()
{
return this.value + "->";
}
}
public static IntNode InsertIntoSortedList(IntNode list, int x)
{
IntNode p = list;
int max = p.GetValue();
Console.WriteLine("hila");
if (p == null)
{
p.SetValue(x);
return p;
}
while(p!=null&& x!=0)
{
Console.WriteLine("hola");
if (x<p.GetNext().GetValue()){
p=p.GetNext();
}
else
{
p.GetNext().SetValue(x);
x = 0;
p= p.GetNext();
}
}
Console.WriteLine("halo");
Console.WriteLine(list.ToString());
return list;
}
static void Main(string[] args)
{
IntNode list = new IntNode(1, new IntNode(4, new IntNode(9, new IntNode(12, new IntNode(72)))));
Console.WriteLine(InsertIntoSortedList(list, 7));
}
}
首先,正如@Luuk提到的,如果你有
toString
节点方法将会非常有用,这样无论你的操作成功与否,你都可以轻松轻松。它可能看起来像这样:
public override string ToString()
{
String ret = "";
IntNode current = this; // Start from the head node
while (current != null)
{
ret += current.GetValue(); // Append the current node's value
if (current.GetNext() != null)
{
ret += " -> "; // Add separator if there's a next node
}
current = current.GetNext(); // Move to the next node
}
return ret;
}
之后我们可以重新实现您添加新节点的功能:
public static IntNode InsertIntoSortedList(IntNode list, int x)
{
IntNode newNode = new IntNode(x);
if (list == null || x <= list.GetValue())
{
newNode.SetNext(list);
return newNode;
}
IntNode current = list;
while (current.GetNext() != null && x > current.GetNext().GetValue())
{
current = current.GetNext();
}
newNode.SetNext(current.GetNext());
current.SetNext(newNode);
return list;
}
您现在可以测试一下:
IntNode list = new IntNode(1, new IntNode(4, new IntNode(9, new IntNode(12, new IntNode(72)))));
IntNode l = InsertIntoSortedList(list, 7);
Console.WriteLine(l);
l = InsertIntoSortedList(l, -2);
Console.WriteLine(l);
l = InsertIntoSortedList(l, 78);
Console.WriteLine(l);
l = InsertIntoSortedList(l, 50);
Console.WriteLine(l);
输出是:
1 -> 4 -> 7 -> 9 -> 12 -> 72
-2 -> 1 -> 4 -> 7 -> 9 -> 12 -> 72
-2 -> 1 -> 4 -> 7 -> 9 -> 12 -> 72 -> 78
-2 -> 1 -> 4 -> 7 -> 9 -> 12 -> 50 -> 72 -> 78