链接列表中的空引用从J​​ava传递到C#

时间:2014-02-08 02:12:01

标签: c# java linked-list nullreferenceexception

我只是将这个链接列表代码从java传递给C#,但是我一直在使用NullReferenceException在 print 方法中得到错误,我是C#的新工作,我不知道是否在方法或可能是代码实现的方式。

节点类

class SLLNode
{
    public int info;
    public SLLNode next;

    public SLLNode() { }

    public SLLNode(int el)
        :this(el, null)
    {

    }

    public SLLNode(int el, SLLNode next)
    {
        this.info = el;
        this.next = next;
    }
}

关联列表类

class SLList
{
    protected SLLNode head;
    protected SLLNode tail;

    public SLList()
    {
        head = tail = null;
    }

    public Boolean isEmpty()
    {
        return head == null;
    }

    public void addToHead(int el)
    {
        if (!isEmpty())
        {
            head = new SLLNode(el, head);
        }
        else
        {
            head = tail = new SLLNode(el);
        }
    }

    public void addToTail(int el)
    {
        if (!isEmpty())
        {
            tail.next = new SLLNode(el);
            tail = tail.next;
        }
        else
        {
            head = tail = new SLLNode(el);
        }
    }

    public String print()
    {
        String str = "";
        for (SLLNode tmp = head; head.next != null; tmp = tmp.next)
        {
            str += ", " + tmp.info;
        }

        return str;
    }
}

1 个答案:

答案 0 :(得分:0)

你的print()方法逻辑在for循环部分有点偏。它正在“递增”tmp变量,但从head.next检查空条件。

for (SLLNode tmp = head; head.next != null; tmp = tmp.next)
{
    str += ", " + tmp.info;
}

head.next的值永远不会改变,所以循环永远不会结束,直到某些东西(例如异常)强制它停止。您应该从tmp检查空条件,所以我认为循环应该是这样的:

for (SLLNode tmp = head; tmp != null; tmp = tmp.next)
{
    str += ", " + tmp.info;
}