[英]Java Linked List search and delete method
我有一個計算機科學課程的項目,除一種方法外,其他所有工作都已完成。 刪除方法。 基本上,我是從用戶輸入中創建一個鏈表,我需要能夠刪除所有節點(已完成)並刪除單個指定節點。 所以我需要在節點列表中搜索找到要刪除的節點並將其刪除。 任何可以幫助的人都表示贊賞。 如果您有解決方案,請在我嘗試學習並解決問題時提供解釋。
我不會為您提供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");
}
}
}
沒有勺子喂你答案。 刪除有點像刪除鏈中的一個鏈接-剪掉該鏈接,然后將兩個(新)端連接起來。
因此,刪除“ B”表示更改
A --> B --> C --> D
對此
A --> C --> D
在偽代碼中,算法為:
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
}
評論應該解釋發生了什么
您需要做的就是搜索列表,跟蹤自己的位置。 當您要刪除的節點在您的前面時,將當前節點的“下一個”設置為要刪除的節點之后的節點:
for(Node current = list; current.next() != null; current = current.next()){
if(current.next().magazine().equals(toDelete)) current.setNext(current.next().next());
}
這樣的事情。 希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.