java - 显示我的 LinkedList 的元素不起作用

标签 java list linked-list

调用remove方法后,我调用display,得到一个空列表;但是,如果我首先调用显示方法,它将显示正确的列表,我猜测“第一个”值到达了列表的末尾,或者我在某处得到了损坏的节点。任何帮助表示赞赏

public class LinkedList {

    private Node first;

    public LinkedList()
    {
        first = null;
    }

    //add students to the list
    public void add(Student s)
    {
        Node newNode = new Node(s);
        newNode.next = first;
        first = newNode;        
    }

    //remove duplicate records (return true if duplicate found)
    public boolean remove(String fn, String ln)
    {
        Student remove;
        boolean found = false;
        int duplicate = 0;
        while(first != null)
        {
            if(first.value.getFname().equals(fn) && first.value.getLname().equals(ln))
            {
                duplicate++;
                if(duplicate > 1)
                {
                    remove = first.value;
                    found = true;  

                }                
            }
            first = first.next;
        }
        if(found)
            return found;
        else
            return found;
    }

    //display list of student
    public void display()
    {
        if(first == null)
            System.out.println("List is empty!");
        else
        {
            while(first != null)
            {
                System.out.println(first.value);
                first = first.next;
            }            
        }            
    }

}

主要内容

public class Tester {


    public static void main(String[] args) {

        UnderGrad john = new UnderGrad("john", "doe", 2.7, "computer Science", "phisics");
        UnderGrad jorge = new UnderGrad("jorge", "vazquez", 3.8, "computer Science", "programming");
        UnderGrad john2 = new UnderGrad("john", "doe", 3.0, "Computer Engineering", "phisics");

        Advisor jim = new Advisor("jim", "smith");

        Grad jane = new Grad("jane", "doe", 3.0, "Electric Engineering", jim);       


        LinkedList students = new LinkedList();

        students.add(john);
        students.add(jorge);
        students.add(john2);
        students.add(jane);


        System.out.println(students.remove("john", "doe"));

        students.display();


    }
}

输出

run:
true
List is empty!
BUILD SUCCESSFUL (total time: 1 second)

最佳答案

您在 remove 方法中使用链表的头 (first) 作为迭代器。相反,使用局部变量:

for (Node current = first; current != null; current = current.next) {
    if (current.value.getFname().equals(...
    ...
    ...
}

关于java - 显示我的 LinkedList 的元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10965394/

相关文章:

java - 如何从链表中删除素数

python - + : 'int' and 'str' 不支持的操作数类型

jquery - 使用 jQuery,如何删除列表项并将其移动到同一列表中的特定位置?

c++ - 使用子类操作类

java - 使用具有相同 hibernate 映射文件的两个不同数据库

java - 为什么 Ant 以错误的顺序运行 testng.xml 中定义的测试类?

java - spring mvc 项目中属性文件的位置

java - 当使用 null 显式初始化时,可序列化类中的映射显示为 Sonar 违规

python - 将 np 矩阵及其索引转换为两个列表

无法防止链表打印功能崩溃