我有一个链表数据结构,我正在测试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。但我知道没有其他办法可以做到这一点;所以任何帮助表示赞赏
答案 0 :(得分:1)
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;
}
答案 1 :(得分:0)
如果你要删除最后一个,你可能想要在第一个中添加一个内部if:
public lList deleteInfo(String outInfo) {
if ( info == outInfo ) {
if( nextList() == null ) {
//delete current list as u want
return this;
}
lList link = nextList().deleteInfo( outInfo );
info = link.info;
nextList = link.nextList();
}
else if ( nextList() != null )
nextList().deleteInfo( outInfo );
return this;
}
答案 2 :(得分:0)
以下是最终对我有用的内容:
//lList : deleteInfo()
//Pre: information to delete
//Post : List not containing information is returned
public lList deleteInfo(String outInfo) {
if ( nextList() != null ) {
lList link = nextList().deleteInfo( outInfo );
if ( nextList().info == outInfo ) { //Handles information that is located at end of list
nextList = link.nextList();
}
else if ( info == outInfo ){//Handles information that is located at beginning of list
info = link.info;
nextList = link.nextList();
}
else nextList().deleteInfo( outInfo );
}
return this;
}
请注意,当只有一个列表且您尝试删除该列表中的信息时,它不起作用。我认为这是一件好事,因为你无法取消引用自我