0

我有一个链表数据结构,我正在测试 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。但我不知道有其他方法可以做到这一点;所以任何帮助表示赞赏

4

3 回答 3

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;
    }
于 2013-05-20T15:28:09.000 回答
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;
    }
于 2013-05-20T15:27:38.213 回答
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;
}

请注意,当只有一个列表并且您尝试删除该列表中的信息时,它不起作用。我认为这是一件好事,因为你不能取消引用 self

于 2013-05-20T18:35:53.953 回答