DEV Community

HunorVadaszPerhat
HunorVadaszPerhat

Posted on

Java - Singly Linked Lists: Showcasing with `printList()` 🌟

Hello Dev.to enthusiasts! 🌟

After exploring adding and deleting nodes in our linked list, today we’re diving into something visually satisfying: displaying. Bring in the spotlight for the printList() method!

Quick Revisit: Singly Linked List πŸ“–

For our newly arrived friends:

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

Unveiling the printList() Method πŸ–¨

Here’s how you display your linked list:

public void printList() {
    // We start at the head of the list
    Node current = head;

    while (current != null) {
        System.out.print(current.data + " -> ");
        current = current.next;
    }

    // And cap it off with "null"
    System.out.println("null");
}
Enter fullscreen mode Exit fullscreen mode

Why a Print Method? 🧐

Visualization is key. Whether you're debugging, ensuring data integrity, or just want to admire the nodes you've worked hard to put together, printList() is your friendly tool to see everything at a glance.

Wrapping Up 🎁

The printList() method lets you stroll through each node, looking into its data. Remember, while data structures can sometimes be tricky, visual feedback makes everything better!

In the next article we will look at find(data) method

Cheers and happy coding! πŸš€

Top comments (0)