DEV Community

HunorVadaszPerhat
HunorVadaszPerhat

Posted on

Java - Singly Linked Lists: Starting at the Top with `prepend(data)` 🎩

Hey there, Dev.to enthusiasts!!! 🌈

Last time, we chatted about appending data to the end of a singly linked list. This time, we’re flipping the script. Let's focus on how to add new nodes at the start of the list using our prepend(data) method.

Quick Rewind: Singly Linked List πŸ“Ό

For those who've just popped in:

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

Picture each node as a small box holding data and pointing to its neighbour (or null if it's feeling a tad antisocial).

The Magic of Prepending πŸͺ„

Prepending is akin to saying, "Hold my place at the front of the line!" Here’s how you do it in Java:

public void prepend(int data) {
    // Create our brand-new node
    Node newNode = new Node(data);

    // New node points to the current head
    newNode.next = head;

    // And voila, it's now the head of the line!
    head = newNode;
}
Enter fullscreen mode Exit fullscreen mode

Why Prepend, Though? 🧐

Sometimes, adding to the start is just more efficient, especially if you're not concerned about the order of elements. Or maybe you have a use case where the most recent data is the most relevant.

Conclusion πŸ‚

Mastering both appending and prepending in your singly linked list toolkit ensures you're prepared for a diverse range of scenarios in coding.

In the next article we will look at deleteWithValue(data) method

Happy coding and till next time! πŸš€

Top comments (0)