【发布时间】:2020-09-18 08:45:26
【问题描述】:
我有这个程序,我的任务是:
- 要创建一个返回列表当前结尾的方法,或者从用于追加的方法中获取列表结尾,将其传递并
- 在将新元素追加到列表的当前末尾后,设置列表实例的末尾值,然后调用该方法以该值追加新的列表项。
class Node
{
string info;
Node next;
public void SetInfo(string InfoNew)
{
info = InfoNew;
next = null;
}
public void Add(string InfoNew)
{
if (next == null)
{
next = new Node();
next.SetInfo(InfoNew);
}
else
next.Add(InfoNew);
}
}
class Program
{
static void Main(string[] args)
{
Node listStart = new Node();
listStart.Add("node 1");
for (int node = 2; node < 4; node++)
listStart.Add("node " + node);
}
}
}
这是我的解决方案。有用。但我不确定这是否正确。
class Node
{
string info;
Node next;
public void SetInfo(string InfoNew)
{
info = InfoNew;
next = null;
}
public Node Add(string InfoNew)
{
if (next == null)
{
next = new Node();
next.SetInfo(InfoNew);
}
else
next.Add(InfoNew);
return next;
}
public void Print()
{
Console.WriteLine(info);
if (next != null)
next.Print();
Console.ReadKey();
}
public Node End()
{
Node ptr = next;
while (ptr.next != null)
ptr = ptr.next;
return ptr;
}
}
class Program
{
static void Main(string[] args)
{
Node listStart = new Node();
Node listEnd = new Node();
listStart.Add("node 1");
for (int node = 2; node < 4; node++)
listEnd = listStart.Add("node " + node);
listStart.Print();
}
}
【问题讨论】:
-
“它有效。但我不确定这是否正确” - 你调试了吗?单元测试?
-
我确实对其进行了调试,并且 Print() 方法显示所有元素都正确。但我不确定 listEnd 是否真的是列表的结尾。如何进行单元测试?
标签: c# linked-list console-application