我正在制作一个简单的程序来刷新我的链表。我的删除学生方法有问题。所有它应该做的是检查两个学生是否有相同的学生ID,如果他们这样做,删除该学生,因为学生是独特的。
我遇到了一个主要问题,那就是如果学生在列表的最后,它会给我各种各样的问题。它似乎也正在删除错误的学生..
方法如下
public boolean remove(StudentIF s) {
// TODO Auto-generated method stub
StudentLLNode current = head;
if(s == null){
return false;
}
if(s.getId() == (head.getStd().getId())){
//StudentLLNode top = head;
head = head.getNext();
size--;
return true;
}
else{
while(current != null){
if(s.getId() == (current.getStd().getId())){
current.setNext(current.getNext().getNext());
size--;
return true;
}
current = current.getNext();
}
}
return false;
}
这是我界面的存根
// remove StudentIF s *** using its equals method ***
public boolean remove(StudentIF s);
答案 0 :(得分:1)
通过做:
current.setNext(current.getNext().getNext());
您似乎正在删除下一个元素而不是当前元素。
当你点击列表的末尾时,getNext()返回null。并且在null之后没有下一个元素,这就是为什么如果到达列表末尾会得到异常的原因。
其他容器更适合避免重复元素。例如,集或地图。
答案 1 :(得分:1)
这是完整的解决方案:
package linkedList;
import java.util.Iterator;
public class StudentList {
private int size = 0;
private StudentIF head;
public StudentList(StudentIF studentTobeAdded) {
head = studentTobeAdded;
size++;
}
public void addStudent(StudentIF studentTobeAdded) {
StudentIF curent = head;
while (curent.getNext() != null) {
curent = curent.getNext();
}
size++;
curent.setNext(studentTobeAdded);
}
public boolean removeStudent(StudentIF studentToBeRemoved)
{
int id = studentToBeRemoved.getId();
StudentIF current = head;
if (head.getId() == id) {
head = head.getNext();
size--;
return true;
}
while (current.getNext() != null) {
StudentIF next = current.getNext();
if (next.getId() == id) {
current.setNext(next.getNext());
size--;
return true;
}
current = next;
}
return false;
}
public int getSize() {
return size;
}
public StudentIF getHead() {
return head;
}
public void addListOfStudents(StudentIF... list) {
for (StudentIF studentIF : list) {
this.addStudent(studentIF);
}
}
@Override
public String toString() {
StudentIF current = head;
StringBuilder sb = new StringBuilder();
while (current != null) {
sb.append(current.getId() + " ");
current = current.getNext();
}
return sb.toString();
}
}
学生:
package linkedList;
public class StudentIF {
private int id;
private StudentIF next;
public StudentIF(int id) {
this.id = id;
next=null;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public StudentIF getNext() {
return next;
}
public void setNext(StudentIF next) {
this.next = next;
}
}
答案 2 :(得分:0)
在你的while循环中,你不处理要删除的学生位于链表末尾的情况,因此current.getNext().getNext()
是NPE。
此外,您的代码并没有删除ID相等的学生,它实际上是在学生之后删除了学生。
以下内容应该可以解决您的困境(尽管尚未编译或测试过)。
...
else {
// head == current and if we get here, the if branch has not fired
StudentLLNode previous, next;
previous = current;
current = current.getNext();
while(current != null){
next = current.getNext();
if(s.getId() == (current.getStd().getId())){
previous.setNext(next); //doesn't matter if next is null or not
size--;
return true;
}
previous = current;
current = next;
}
...