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