java - Java从单链表中删除第一个节点

标签 java data-structures linked-list nodes

我有一个链表数据结构,我正在测试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/

相关文章:

java - javacast如何工作,是改变对象的状态还是创建新的对象?

c - 编写一个重新排列链表的函数,将偶数位置的节点放在列表中奇数位置的节点之后

c - 在C中用栈实现链表

java - 显式等待无法正常工作

java使用平面文件中的父ID创建多个树状结构

java - 在移动应用程序中高效的本地存储和 map 访问?

c - 使用 C 对链表进行排序

java - 是否有一些更好的方法可以在您使用相当小的数据集输入 Java 时实现查找?

c - 链表: Moving a node from one list to another

java - 映射减少编程错误