创建一个返回监听的方法。并改变它使用监听的添加方法

时间:2020-09-18 08:45:26

标签: c# linked-list console-application

我有这个程序,我的任务是:

  1. 要创建一种方法,该方法返回列表的当前末尾或从方法中获取列表的末尾以进行附加,以使其交付和
  2. 要在将新元素附加到列表的当前末尾之后设置列表实例末尾的值,然后调用该方法以使用该值附加新列表项。
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();
    }
}

1 个答案:

答案 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();
    }
}