How to delete a specific node from a singly linked list…
To delete a node in a singly linked list, you can follow these steps:
- Firstly check if the node to be deleted is the head node. If it is the head node, simply point the head pointer to the next node.
- If the node to be deleted is not the head node, you first need to find the node before the one you want to delete.
- Point the next pointer of the previous node to the next node of the node to be deleted, skipping over the node to be deleted.
- Free up the memory space of the node to be deleted to complete the deletion operation.
Here is an example code:
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;
}
}
Example of Use:
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;
}
}
}
The output is: 1 3, indicating that the node with the value of 2 was successfully deleted.