我有一个计算机科学课项目,除了一种方法外,我什么都做完了。删除方法。基本上我正在从用户输入创建一个链接列表,我需要能够删除所有节点(已完成)并删除单个指定节点。所以我需要在节点列表中搜索找到要删除的节点并删除它。任何可以提供帮助的东西都会受到赞赏。如果您有解决方案,请提供解释,因为我正在努力学习并解决问题。
我不会给你 GUI,因为我认为没有必要,但这里是节点类。
public class MagazineList {
private MagazineNode list;
public MagazineList(){
list = null;
}
public void add(Magazine mag){
MagazineNode node = new MagazineNode(mag);
MagazineNode current;
if(list == null) {
list = node;
}
else {
current = list;
while(current.next != null)
current = current.next;
current.next = node;
}
}
public void insert(Magazine mag) {
MagazineNode node = new MagazineNode (mag);
// make the new first node point to the current root
node.next=list;
// update the root to the new first node
list=node;
}
public void deleteAll() {
if(list == null) {
}
else {
list = null;
}
}
public void delete(Magazine mag) {
//Delete Method Goes Here
}
public String toString(){
String result = " ";
MagazineNode current = list;
while (current != null){
result += current.magazine + "\n";
current = current.next;
}
return result;
}
private class MagazineNode {
public Magazine magazine;
public MagazineNode next;
public MagazineNode(Magazine mag){
magazine = mag;
next = null;
}
}
}
更新
这是我放在一起的方法,它通过第一部分进入 while 循环,并且永远不会识别列表中的相同项目。我对输入和删除方法使用了完全相同的东西,但它不会识别它。任何帮助表示赞赏。
public void delete (Magazine mag) {
MagazineNode current = list;
MagazineNode before;
before = current;
if(current.equals(mag)){
before.next = current;
System.out.println("Hello");
}
while ((current = current.next)!= null){
before = current.next;
System.out.println("Hello Red");
if(current.equals(mag)){
current = before;
System.out.println("Hello Blue");
}
}
}