【问题标题】:Create a method to return listend. And change adding method that it uses listend创建一个方法来返回监听。并更改它使用的添加方法
【发布时间】:2020-09-18 08:45:26
【问题描述】:

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

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

【问题讨论】:

  • “它有效。但我不确定这是否正确” - 你调试了吗?单元测试?
  • 我确实对其进行了调试,并且 Print() 方法显示所有元素都正确。但我不确定 listEnd 是否真的是列表的结尾。如何进行单元测试?

标签: c# linked-list console-application


【解决方案1】:

这可能是正确的做法,不是吗?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    • 2012-08-30
    • 2014-04-06
    • 1970-01-01
    相关资源
    最近更新 更多