Hi there. Thank you all for your comments. The problem solved and I also learn something new about editing and formatting. I want to thumb up every comment and close the post but I did not figure out how to do so, so I will do it later.
//My original problem below I cannot print out the data in the last node of the singly linked list when I try to code in the main. Just comment the display method and you will see my original code.
I can only print out all the data when I use the display method outside of the main. Please explain to me why the display method works and the other way doesn't.
Below is my code
package learnSingleLinkedList;
public class SinglyLinkedList {
private ListNode head;
private static class ListNode
{
private int data;
private ListNode next;
ListNode(int data)
{
this.data = data;
this.next = null;
}
}
public void display()
{
ListNode current = head;
while(current!=null)
{
System.out.print(current.data+" --> ");
current = current.next;
}
System.out.print("Null");
}
public static void main(String[] args)
{
SinglyLinkedList sll = new SinglyLinkedList();
sll.head = new ListNode(10);
ListNode second = new ListNode(1);
ListNode third = new ListNode(8);
ListNode fourth = new ListNode(11);
sll.head.next = second;
second.next = third;
third.next = fourth;
fourth.next = null;
ListNode current = sll.head;
while(current.next != null)
{
System.out.println(current.data);
current = current.next;
}
sll.display();
}
}