在Java中,我們可以使用鏈表數(shù)據(jù)結(jié)構(gòu)來實(shí)現(xiàn) ListNode。要實(shí)現(xiàn)節(jié)點(diǎn)刪除,我們需要遵循以下步驟:
以下是一個(gè)簡單的實(shí)現(xiàn):
// 定義 ListNode 類
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
// 定義鏈表類
class LinkedList {
ListNode head;
// 添加節(jié)點(diǎn)到鏈表頭部
public void add(int val) {
ListNode newNode = new ListNode(val);
newNode.next = head;
head = newNode;
}
// 刪除指定值的節(jié)點(diǎn)
public void delete(int val) {
if (head == null) {
return;
}
// 如果頭節(jié)點(diǎn)就是要?jiǎng)h除的節(jié)點(diǎn)
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;
}
}
// 查找指定值的節(jié)點(diǎn)
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