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;
}
}
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;
}
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)