LinkedList .Add()只运行一次

时间:2014-06-10 04:45:29

标签: c# linked-list

我正在制作基本的LinkedList this教程。但是,当我完成后,list只包含两个元素"first""fourth"。我在代码中放了一些断点,发现Add类的LinkedList函数只运行一次。每个成功的Add都会进入Node(object data)类的Node方法。知道我做错了什么吗?

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

2 个答案:

答案 0 :(得分:0)

将此基本打印方法与您的代码一起使用:

public void Print()
{
    Node curr = head;
    while(true)
    {
        if(curr == null)
           return;
         Console.WriteLine(curr.data.ToString());
         curr = curr.next;
    }
}

返回正确的结果:live example

  

首先

     

第二

     

第三

     

第四

您的错误必须与您的打印程序有关。

答案 1 :(得分:0)

您的代码没有问题,我猜您在调试时只检查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();
        }

    }