简体   繁体   中英

Null Refence in Linked List passing from Java to C#

I just pass this linked list code from java to C# but I keep getting errors in the print method with a NullReferenceException, I am new working with C#, I dont know if the error if in the method or probably it is way that the code is implemented.

Node Class

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

Linked List Class

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

Your print() method logic is a bit off in for loop part. It is "incrementing" tmp variable, but check null condition from head.next .

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

Value of head.next is never change, so the loop will never end until something (exception for example) force it to stop. You should check null condition from tmp instead, so I think the loop should've been this way :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM