C# LinkedList.Add()只运行一次

C# LinkedList.Add()只运行一次,c#,linked-list,C#,Linked List,在接下来的教程中,我正在制作一个基本的LinkedList。但是,当我完成时,列表只包含两个元素,“第一个”和“第四个”。我在代码中放了一些断点,发现LinkedList类的Add函数只运行一次。每个后续的Add进入节点(对象数据)方法的节点类。知道我做错了什么吗 public class Node { public object data; public Node next; public Node(object data) { this.dat

在接下来的教程中,我正在制作一个基本的
LinkedList
。但是,当我完成时,
列表只包含两个元素,
“第一个”
“第四个”
。我在代码中放了一些断点,发现
LinkedList
类的
Add
函数只运行一次。每个后续的
Add
进入
节点(对象数据)
方法的
节点
类。知道我做错了什么吗

public class Node
{
    public object data;
    public Node next;
    public Node(object data)
    {
        this.data = data;
    }
}
public class LinkedList
{
    private Node head;
    private Node current;
    public void Add(Node n)
    {
        if (head == null)
        {
            head = n;
            current = head;
        }
        else
        {
            current.next = n;
            current = current.next;
        }
    }
}


class Program
{
    static void Main(string[] args)
    {
        LinkedList list = new LinkedList();
        list.Add(new Node("first"));
        list.Add(new Node("second"));
        list.Add(new Node("third"));
        list.Add(new Node("fourth"));
    }
}

在代码中使用此基本打印方法:

public void Print()
{
    Node curr = head;
    while(true)
    {
        if(curr == null)
           return;
         Console.WriteLine(curr.data.ToString());
         curr = curr.next;
    }
}
返回正确的结果:

首先

第二

第三

第四


您的错误一定与打印例程有关。

您的代码没有问题,我猜您在调试时只检查了LinkedList节点,这将只显示头和当前值

试试这个

 class Program
    {
        static void Main(string[] args)
        {
            LinkedList list = new LinkedList();
            list.Add(new Node("first"));
            list.Add(new Node("second"));
            list.Add(new Node("third"));
            list.Add(new Node("fourth"));
            list.PrintNodes();
        }

    }
    public class Node
    {
        public object data;
        public Node next;
        public Node(object data)
        {
            this.data = data;
        }
    }
    public class LinkedList
    {
        private Node head;
        private Node current;
        public void Add(Node n)
        {
            if (head == null)
            {
                head = n;
                current = head;
            }
            else
            {
                current.next = n;
                current = current.next;
            }

        }
        public void PrintNodes()
        {
            while (head != null)
            {

                Console.WriteLine(head.data);
                head = head.next;

            }
            Console.ReadLine();
        }

    }

您如何得到
列表只包含两个元素的答案,“第一”和“第四”
?PrintNodes方法可能有问题吗?是否有其他代码没有显示给我们,用于修改当前的
?如果有,它很有可能让Add做错事。