的引用
我有一个链表数据结构,我正在测试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;
}
你可能想要在第一个if中添加一个内部if来检查你是否删除了最后一个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;
}
这是我最终成功的方法:
//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;
}
请注意,当只有一个列表并且您试图删除该列表中的信息时,它不起作用。我认为这是件好事因为你不能取消对self