1

我看到以下错误:

你调用的对象是空的!

在调用方法之前检查以确定对象是否为空!

我为排序链接列表制作了一个小型测试程序。这是错误出现的代码!

    public void Insert(double data)
    {
        Link newLink = new Link(data);
        Link current = first;
        Link previous = null;

        if (first == null)
        {
            first = newLink;
        }
        
        else
        {
            while (data > current.DData && current != null)
            {
                previous = current;
                current = current.Next;
            }

            previous.Next = newLink;
            newLink.Next = current;
        }
    }

它说当前的引用是 null while (data > current.DData && current != null),但我分配了它:current = first;

剩下的就是程序的完整代码了!

class Link
{
    double dData;
    Link next=null;

    public Link Next
    {
        get { return next; }
        set { next = value; }
    }

    public double DData
    {
        get { return dData; }
        set { dData = value; }
    }

    public Link(double dData)
    {
        this.dData = dData;
    }


    public void DisplayLink()
    { 
    Console.WriteLine("Link : "+ dData);
    }

}

class SortedList
{
    Link first;

    public SortedList()
    { 
        first = null;
    }

    public bool IsEmpty()
    {
        return (this.first == null);
    }

    public void Insert(double data)
    {
        Link newLink = new Link(data);
        Link current = first;
        Link previous = null;

        if (first == null)
        {
            first = newLink;
        }
        
        else
        {
            while (data > current.DData && current != null)
            {
                previous = current;
                current = current.Next;
            }

            previous.Next = newLink;
            newLink.Next = current;
        }
    }

    public Link Remove()
    {
        Link temp = first;
        first = first.Next;
        return temp;
    }

    public void DisplayList()
    {
        Link current;
        current = first;

        Console.WriteLine("Display the List!");
        
        while (current != null)
        {
            current.DisplayLink();
            current = current.Next;
        }
    }
}

class SortedListApp
{
    public void TestSortedList()
    {
        SortedList newList = new SortedList();
        newList.Insert(20);
        newList.Insert(22);
        newList.Insert(100);
        newList.Insert(1000);
        newList.Insert(15);
        newList.Insert(11);

        newList.DisplayList();
        newList.Remove();
        newList.DisplayList();

    }
}
4

2 回答 2

1

同意你已经完成

current = first; 

但是你的课程的开头首先是空的

class SortedList
{
    Link first;

请分配一些东西,first否则它将为空

于 2012-10-25T23:02:59.597 回答
1

您可能会假设 while 循环在第一次迭代时中断,这并不是 while 循环中的赋值最终会中断它。

根据您的代码,最终 current 为 NULL,您甚至可以对其进行测试 - 将其更改为此应该没问题:

while (current != null && data > current.DData)
{
    previous = current;
    current = current.Next;
}
于 2012-10-25T23:07:31.890 回答