import java.io.*; public class LinkedList { private class node { int number; node next; } private node current = new node(); LinkedList() { current=null; } public void insert(int n) { if(current != null) { while(current != null) { current = current.next; } current = new node(); current.number = n; current.next = null; } else { current = new node(); current.number = n; current.next = null; } } public void PrintList() { int count = 0; while(current != null) { System.out.println(current.number); current=current.next; count++; System.out.println(count); } } public static void main(String[] args) { LinkedList myList=new LinkedList(); for(int i=0;i<10;i++) { myList.insert(i); } myList.PrintList(); } }
This compiles but it only runs once it seems. The program outputs 9 which is the end of the loop in main and 1 which counts how many times the while loop happens in the print method. Therefore I must be overriding the same memory location in my insert method, but why?
--- Update ---
I changed a few things around but still the same result:
import java.io.*; public class LinkedList { private class node { int number; node next; } private node current = new node(); LinkedList() { current=null; } public void insert(int n) { if(current==null) { current = new node(); current.number = n; current.next = null; } else { while(current != null) { current = current.next; } current = new node(); current.number = n; current.next = null; } } public void PrintList() { int count = 0; while(current != null) { System.out.println(current.number); current=current.next; count++; System.out.println(count); } } public static void main(String[] args) { LinkedList myList=new LinkedList(); for(int i=0;i<10;i++) { myList.insert(i); } myList.PrintList(); } }