DEV Community

HunorVadaszPerhat
HunorVadaszPerhat

Posted on

Java - ๐Ÿ”„ `reverse()`: Turning Your Singly Linked List World Upside Down ๐Ÿ™ƒ

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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)