在Java中,我們可以使用鏈表數據結構來實現 ListNode。要實現節點刪除,我們需要遵循以下步驟:
以下是一個簡單的實現:
// 定義 ListNode 類
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
// 定義鏈表類
class LinkedList {
ListNode head;
// 添加節點到鏈表頭部
public void add(int val) {
ListNode newNode = new ListNode(val);
newNode.next = head;
head = newNode;
}
// 刪除指定值的節點
public void delete(int val) {
if (head == null) {
return;
}
// 如果頭節點就是要刪除的節點
if (head.val == val) {
head = head.next;
return;
}
ListNode current = head;
while (current.next != null) {
if (current.next.val == val) {
current.next = current.next.next;
return;
}
current = current.next;
}
}
// 查找指定值的節點
public ListNode find(int val) {
ListNode current = head;
while (current != null) {
if (current.val == val) {
return current;
}
current = current.next;
}
return null;
}
}
使用示例:
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
System.out.println("Original list:");
printList(list);
list.delete(2);
System.out.println("List after deleting 2:");
printList(list);
}
// 打印鏈表
public static void printList(LinkedList list) {
ListNode current = list.head;
while (current != null) {
System.out.print(current.val + " -> ");
current = current.next;
}
System.out.println("null");
}
}
輸出:
Original list:
1 -> 2 -> 3 -> 4 -> null
List after deleting 2:
1 -> 3 -> 4 -> null