首页 > 解决方案 > Java - 以升序运行插入节点时出现运行时错误

问题描述

我正在尝试按升序插入节点,但是它不起作用。

这是来自主程序的代码:

LinearList lst= new LinearList();
    Random r = new Random();
    for (int x=0; x<10;x++)
    {
        AnyClass ax = new AnyClass(r.nextInt(201));
        lst.insertAscOrder(ax);

    }
        lst.showList();

java.util*; 已导入。这是来自 LinearList 类的代码:

public void insertAscOrder(AnyClass obj)
{
    Node newNode = new Node(obj);
    if(head==null) //if list is empty
    {
        head=newNode;
    }
    else
    {
        Node tthis=head;
        Node prev=head;
        while(tthis!=null)
        {
            if(tthis.obj.getKey().compareTo(newNode.obj.getKey())>=0)
            {
                if(tthis==prev)//if first node
                {
                    newNode.next=head;
                    head=newNode;
                }
                else //if you're inserting not before first node
                {
                    newNode.next=tthis;
                    prev.next=newNode;
                }
            }
            else //if key of this< key of newNode
            {
                prev=tthis;
                tthis=tthis.next;
            }

        }

    }
}

我认为问题不是 Random 类,因为我已经对其进行了测试,并且循环只迭代了两次。

标签: javaruntime

解决方案


您错过了在列表末尾插入的情况。尝试浏览代码,了解插入时会发生什么1, 2(按该顺序)。当 while2循环的条件变为假时,您永远不会插入。

此外,您必须break在成功插入元素后。

可以有多种方法来解决这个问题。这是一种方法。

while(tthis!=null)
{
    if(tthis.obj.getKey().compareTo(newNode.obj.getKey())>=0)
    {
        if(tthis==prev)//if first node
        {
            newNode.next=head;
            head=newNode;
        }
        else //if you're inserting not before first node
        {
            newNode.next=tthis;
            prev.next=newNode;
        }
        break; //breaking and not further looping
    }
    else //if key of this< key of newNode
    {
        prev=tthis;
        tthis=tthis.next;
    }
}
if (tthis == null) { //This means that we have reached the end of the list without inserting the element
  prev.next = newNode; //Create the link from the last node.
}

推荐阅读