要刪除單鏈表中的某個節點,可以按照以下步驟進行操作:
以下是一個示例代碼:
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class LinkedList {
private ListNode head;
public void deleteNode(int val) {
ListNode current = head;
ListNode previous = null;
// 遍歷鏈表找到要刪除的節點和其前一個節點
while (current != null && current.val != val) {
previous = current;
current = current.next;
}
// 要刪除的節點是頭節點
if (current == head) {
head = head.next;
}
// 要刪除的節點不是頭節點
else {
previous.next = current.next;
}
// 釋放要刪除的節點的內存空間
current = null;
}
}
使用示例:
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
// 添加節點
list.head = new ListNode(1);
ListNode second = new ListNode(2);
ListNode third = new ListNode(3);
list.head.next = second;
second.next = third;
// 刪除節點
list.deleteNode(2);
// 打印鏈表
ListNode current = list.head;
while (current != null) {
System.out.print(current.val + " ");
current = current.next;
}
}
}
輸出結果為:1 3,表示成功刪除了值為2的節點。