DEV Community

HunorVadaszPerhat
HunorVadaszPerhat

Posted on

Java - Singly Linked Lists: How to Append Like a Pro! πŸ’Ύ

Hello again, Dev.to enthusiasts! 🌌

Continuing our journey with singly linked lists, let's discuss a key operation that I like to call "Add to the End." a'la append(data) method.

A Quick Refresher: Singly Linked List πŸ“˜

For those who've just joined 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

Each node in our list holds some data and a pointer to the next node, or null if it's the last one in line.

The Art of Appending πŸ–‹

Appending is essentially adding a new node at the end of our list. Here's how you can perform this dance in code:

public void append(int data) {
    // Let's create our shiny new node
    Node newNode = new Node(data);

    // If the list has the "I'm new here" vibes (is empty), make this node the head
    if (head == null) {
        head = newNode;
        return;
    }

    // If not, let's find the end of our list
    Node lastNode = head;
    while (lastNode.next != null) {
        lastNode = lastNode.next;
    }

    // Once we're at the end, let's welcome our new node
    lastNode.next = newNode;
}
Enter fullscreen mode Exit fullscreen mode

Why Appending? 🀷

Appending is like adding another chapter to your book. As your data grows and evolves, you'll often find yourself needing to add elements. Knowing how to efficiently append to your list ensures that your data structure remains dynamic and responsive to changes.

Wrapping Up 🎁

With the power of appending, you can now let your singly linked list grow gracefully, always adding new data at the tail end.

In the next article we will look at prepend() method

Happy coding and till next time! πŸš€

Top comments (0)