DEV Community

HunorVadaszPerhat
HunorVadaszPerhat

Posted on

Java - Singly Linked Lists: Goodbyes with `deleteWithValue(data)` 🌊

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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)