我有一个链表数据结构,我正在测试deleteInfo()函数。但是,当我尝试删除链接列表中的最后一项时,出现错误。链接列表通过从顶部插入来增长,因此本例中的最后一项实际上是插入的第一项。
这是代码:
public lList deleteInfo(String outInfo) {
if ( info == outInfo ) {
lList link = nextList().deleteInfo( outInfo );
info = link.info;
nextList = link.nextList();
}
else if ( nextList() != null )
nextList().deleteInfo( outInfo );
return this;
}
public void insert(String in_Info) {
if ( isEmpty() == false ) {
lList entry = new lList(); // New entry is created to store new list
entry.info = info; //Store the current list's information into this list
entry.nextList = nextList;
nextList = entry; //Next list now points to the entry created
}
info = in_Info;
}
public lList nextList() {
if ( isEmpty() == false )
return nextList;
return null;
}
有人可以告诉我一种允许删除最后一个列表的方法吗?我知道问题出在第一个 if 语句中,因为它可能试图访问空列表,因为最后一个列表没有 nextList。但我不知道有其他方法可以做到这一点;所以非常感谢任何帮助
最佳答案
public lList deleteInfo(String outInfo) {
if ( nextList() != null && nextList().info == outInfo ) {
lList link = nextList();
nextList = link.nextList();
}
else if (nextList() != null){
nextList().deleteInfo( outInfo );
}
return this;
}
关于java - Java从单链表中删除第一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16652757/