1
protected void sortHorseList(int iHorseCount)
{
    int i = 0;
    Horsie currentNode = head;
    Horsie auxNode = new Horsie();
    boolean foundChange = true;
    while(foundChange)
    {
        foundChange = false;
        for(i=0; i<iHorseCount-1; i++)
        {
            if (currentNode.getHorseValue() > currentNode.getNext().getHorseValue())
            {
                auxNode.setHorseValue(currentNode.getHorseValue());
                currentNode.setHorseValue(currentNode.getNext().getHorseValue());
                currentNode.getNext().setHorseValue(auxNode.getHorseValue());
                foundChange = true;
            }
            currentNode = currentNode.getNext();
        }
    }
}

此代码在运行主程序时显示空指针错误。我是数据结构的新手,我希望在你们的帮助下解决这个问题!请教我如何在双向链表中使用冒泡排序...HEEELP!

4

1 回答 1

1

当您到达列表的末尾时,您不会检查下一个元素是否存在。因此,当您尝试访问它的值时,您会得到空引用异常。你的内部循环应该看起来像

   Horsie currentNode = head;
   Horsie nextNode = currentNode != null ? currentNode.getNext() : null;
   while (currentNode != null && nextNode != null)
    {
        if (currentNode.getHorseValue() > nextNode.getHorseValue())
        {
            currentNode = Swap(head,currentNode,nextNode);
            foundChange = true;
        }
        else
        {
            currentNode = nextNode;
        }
        nextNode = currentNode.getNext();
    }

WhereSwap(Horsie current, Horsie next)交换列表中 和 的位置current,如果是头节点next,则可选地更新头。current

我还要注意,您确实希望交换列表中的节点,而不是交换节点之间的值,除非您确定您的列表包含对节点对象的唯一引用。如果你不这样做,你就会冒着让其他类持有的对象意外变异的风险,因为你在排序过程中改变了它的值。

于 2013-04-13T17:42:43.580 回答