java - 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 类,因为我已经对其进行了测试,并且循环只迭代了两次。
解决方案
您错过了在列表末尾插入的情况。尝试浏览代码,了解插入时会发生什么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.
}
推荐阅读
- node.js - paytm付款成功后,我无法回到我的角度应用程序
- javascript - 带有 Express 的 Node.js:req.body 未定义
- asp.net - 在 web.config 提供程序连接字符串中转义双引号
- python - 基于索引和另外 2 列的列的平均值
- d3.js - 在 svelte 上使用 Leaflet-d3
- sql-server - 如何使用 sql server 2016 比较基于两个关键列的单个列的数据?
- utf-8 - WSO2 MI 正在替换土耳其字符,即使请求 json 中的 charset=UTF-8
- python - python conda - 创建了一个新环境,但它仍然在基础环境中使用 python
- django - 如何在 django 的一个页面中提交相同的表单
- linkedin - 如何通过php中的api获取用户链接帐户的个人资料标题