Hello Dev.to enthusiasts! π
We've spoken about adding to our singly linked list. Today, let's tackle the slightly heartbreaking act of saying goodbye, or more technically, deleting nodes. Introducing...(drum-roooolls) the deleteWithValue(data)
method.
A Quick Refresher: Singly Linked List π
Just in case someone's late to the party:
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class SinglyLinkedList {
Node head;
SinglyLinkedList() {
this.head = null;
}
}
The Delicate Art of Deletion π
Deleting a node is all about finding it first, and then, well, letting it go. Let's delve into the method:
public void deleteWithValue(int data) {
// If the list is playing hide and seek (is empty), there's nothing to delete
if (head == null) return;
// If the head node is our target
if (head.data == data) {
head = head.next;
return;
}
// If not, we go on finding our node
Node current = head;
while (current.next != null && current.next.data != data) {
current = current.next;
}
// If the node isn't found, we exit the stage
if (current.next == null) return;
// Finally... snip it out of the list
current.next = current.next.next;
}
Why Delete? π
Sometimes, data changes. Maybe a value is no longer relevant, or perhaps there's an error in your dataset. In such times, it's crucial to have the ability to cleanly and efficiently remove specific nodes from your list.
To Wrap It Up π
The deleteWithValue(data)
method may seem like a simple tool, but it ensures our singly linked list remains relevant and error-free.
In the next article
we will look at printlist()
method
Cheers and happy coding! π
Top comments (0)