共計 1228 個字符,預計需要花費 4 分鐘才能閱讀完成。
在 Java 中,可以使用 LinkedList 類或者自定義鏈表類來實現鏈表,并且刪除某一個節點可以按照以下步驟進行操作:
-
首先找到要刪除的節點,可以使用循環遍歷鏈表,直到找到要刪除的節點為止。
-
找到要刪除的節點后,將該節點的前一個節點的 next 指針指向要刪除節點的下一個節點。
-
釋放要刪除的節點的內存空間,即將該節點的引用置為 null。
下面是一個示例代碼,演示如何刪除鏈表中的某一個節點:
class Node {int data;
Node next;
public Node(int data) {this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
// 在鏈表末尾添加節點
public void add(int data) {Node newNode = new Node(data);
if (head == null) {head = newNode;} else {Node current = head;
while (current.next != null) {current = current.next;}
current.next = newNode;
}
}
// 刪除指定節點
public void delete(int data) {Node current = head;
Node previous = null;
while (current != null) {if (current.data == data) {if (previous == null) {// 要刪除的節點是頭節點
head = current.next;
} else {previous.next = current.next;}
current = null; // 釋放內存空間
return;
}
previous = current;
current = current.next;
}
}
// 打印鏈表
public void display() {Node current = head;
while (current != null) {System.out.print(current.data + " ");
current = current.next;
}
System.out.println();}
}
public class Main {public static void main(String[] args) {LinkedList list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.display(); // 輸出:1 2 3
list.delete(2);
list.display(); // 輸出:1 3
}
}
在上面的示例代碼中,首先創建了一個自定義的 LinkedList 類,其中 Node 類表示鏈表的節點。在 delete 方法中,首先使用兩個指針 current 和 previous 來遍歷鏈表,找到要刪除的節點,然后修改指針的指向來刪除節點。最后,在 delete 方法中使用 current = null 來釋放內存空間。
丸趣 TV 網 – 提供最優質的資源集合!
正文完