我有一个计算机科学课程,除了一种方法外,我已经完成了所有工作。删除方法。基本上我是从用户输入制作链表,我需要能够删除所有节点(已完成)并删除单个指定节点。所以我需要在节点列表中搜索找到要删除的节点并将其删除。任何有用的东西都值得赞赏。如果您有解决方案,请提供解释,因为我正在努力学习并解决问题。
我不打算给你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");
}
}
}
答案 0 :(得分:5)
没有勺子给你答案。删除有点像删除一个链的一个链接 - 你切断链接并加入两个(新的)结束。
因此,删除“B”意味着改变
A --> B --> C --> D
到这个
A --> C --> D
在伪代码中,算法将是:
答案 1 :(得分:3)
public void delete (Magazine mag) {
MagazineNode current = this.list;
MagazineNode before;
//if is the first element
if (current.equals(mag)) {
this.list = current.next;
return; //ending the method
}
before = current;
//while there are elements in the list
while ((current = current.next) != null) {
//if is the current element
if (current.equals(mag)) {
before.next = current.next;
return; //endind the method
}
before = current;
}
//it isnt in the list
}
评论应该解释发生了什么
答案 2 :(得分:2)
您需要做的就是搜索列表,跟踪您的位置。当您要删除的节点位于您的前面时,将当前节点的“下一个”设置为您要删除的节点之后的节点:
for(Node current = list; current.next() != null; current = current.next()){
if(current.next().magazine().equals(toDelete)) current.setNext(current.next().next());
}
这样的事情。 希望有所帮助!