gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:30:59 24 4
gpt4 key购买 nike

调用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com