A very simple solution is to override
the toString()
method in the Node
. Then, you can call print by passing LinkedList
's head
.
You don't need to implement any kind of loop.
Code:
public class LinkedListNode {
...
//New
@Override
public String toString() {
return String.format("Node(%d, next = %s)", data, next);
}
}
public class LinkedList {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.insertFront(0);
l.insertFront(1);
l.insertFront(2);
l.insertFront(3);
//New
System.out.println(l.head);
}
}