我有这个程序,我的任务是:
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();
}
}
答案 0 :(得分:0)
这可能是正确的方法,不是吗?
class Program
{
static void Main(string[] args)
{
Node listStart = new Node();
Node listEnd = new Node();
listStart.Add("node 1");
listEnd = listStart;
for (int node = 2; node < 4; node++)
listEnd = listEnd.Add("node " + node);
listStart.Print();
}
}