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