I am learning linked list and wrote a sample code to understand the fundamentals. My code works, but is there another way to print out the list using a for loop without the while loop?
I cheated using the for loop I made, because I already knew the number of nodes in the list. Is there a different way of printing the list using a for loop?
public class FriendNode {
FriendNode next;
String name;
FriendNode(String name)
{
this.name = name;
this.next = null;
}
public FriendNode(String name, FriendNode n)
{
this.name = name;
this.next = n;
}
public FriendNode getNext()
{
return this.next;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
FriendNode g = new FriendNode("Bob");
FriendNode o = new FriendNode("Alice");
FriendNode k = new FriendNode("Tom");
FriendNode m = new FriendNode("Day");
g.next = o;
o.next = k;
k.next = m;
m.next = null;
FriendNode current=g;
while(current!=null)
{
System.out.println(current);
current = current.next;
}
for(int i =0; i<4;i++)
{
System.out.println(current);
current = current.next;
}
}
}
NullPointerExceptionbecause it dereferencescurrent, but the first loop will not exit untilcurrentisnull.