Hello Dev.to enthusiasts! 🌟
In our coding lives, there are times when we desire precision. When inserting data 🩺 in a data structure, we want control. Enter the realm of insertAt(index, data)
for the singly linked list.
🏰 Quick Castle Tour: The Singly Linked List
A tiny refresher for our wandering minds (like mine!):
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class SinglyLinkedList {
Node head;
SinglyLinkedList() {
this.head = null;
}
}
🧐 Decoding insertAt(index, data)
Here's our blueprint:
public void insertAt(int index, int data) {
Node newNode = new Node(data);
// If the list is empty or you're adding right at the front
if (head == null || index == 0) {
newNode.next = head;
head = newNode;
return;
}
Node current = head;
int count = 0;
// Loop through the list until you find the perfect node or reach the end
while (current != null && count < index - 1) {
current = current.next;
count++;
}
// Found the spot? Great!
if (current != null) {
newNode.next = current.next;
current.next = newNode;
}
}
🤔 Why Embrace insertAt(index, data)
?
Flexibility 🤸♂️. Rather than always adding rooms to the end or the beginning, this method gives us the freedom to choose our exact position.
💡 Wrapping Up
The insertAt(index, data)
method is like having a precision tool 🔍 in your coding toolkit.
In the next article
we will look at removeAt(index)
method
Cheers and happy coding! 🚀
Top comments (0)