在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