Hello Dev.to enthusiasts! ๐
Ever wished to rewind time? (Well, u know...every now and than...) Maybe to re-live a moment or just to see things from a new perspective. In the realm of data structures, we can indeed turn back time โ or at least our lists.๐ Say hello to (drum-roool please!) reverse()
.
๐ Quick Train Stop: Our Singly Linked List Station
For those who hopped on mid-journey, a whistle-stop tour:
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 (a carriage ๐ in a train) in our list holds some data and a pointer to the next node, or null if it's the last one in line.
๐ Making Sense of reverse()
Let's decipher mechanism:
public void reverse() {
Node prev = null;
Node current = head;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}
Imagine: you're re-arranging carriages of a train. You unhook, then move to a new position and continue until your entire train is arranged in the opposite order.
๐ค Why reverse()
?
Sometimes, to move forward, we need to look back โฎ (I know I now it is clichรฉ
). If it's for algorithmic needs reversing a list can give fresh insight.
Keep exploring, flip things around once in a while, and always remain curious! ๐
Top comments (0)