// Insert at tail of list - the iterative version... import java.io.*; class ListElement { int value; ListElement next; } class Linklist2 { static ListElement Insert(ListElement head, ListElement newelem) { ListElement ptr; // local variable to run down the list if (head == null) { // Empty list, make "newelem" the first element newelem.next = null; // Mark last element return(newelem); } else { // find the last element ptr = head; while (ptr.next != null) ptr = ptr.next; ptr.next = newelem; // Link new to the last element newelem.next = null; // Mark last element return(head); } } public static void Print(ListElement head) { while (head != null) { System.out.print(head.value + " "); head = head.next; } System.out.println(); } public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); ListElement head, ptr; head = null; // Start with an empty list.... while(true) { ptr = new ListElement(); // Make a new list element System.out.print("Enter number: "); ptr.value = Integer.parseInt(stdin.readLine()); head = Insert(head, ptr); // Insert into list System.out.print("List: "); Print(head); System.out.println(); } } }