// File: TestList.java // // Author: Rahul Simha // Created: Sept 21, 1998 // // A linked list in Java. // This is a "node" in the list. class ListItem { public int data; // Integer data field. ListItem next; // The familiar "next" pointer. // This is "singly-linked". } // We will write the code for creating and printing // the list inside "main". public class TestList { public static void main (String[] argv) { // We need "front" and "rear" pointers. ListItem front = null; ListItem rear = null; // Let's add the numbers 1 to 10. for (int i=1; i <= 10; i++) { if (front == null) { // List empty. front = new ListItem (); // Create listnode. front.data = i; // Assign value. rear = front; rear.next = null; } else { // List non-empty. rear.next = new ListItem (); // Create listnode at rear. rear.next.data = i; // Assign value. rear.next.next = null; rear = rear.next; // Adjust rear pointer. } } // Print the contents. ListItem listPtr = front; // Start from front. int i = 1; while (listPtr != null) { System.out.println ("item# " + i + ": " + listPtr.data); i++; listPtr = listPtr.next; // Walk to next item. } } // "main" } // End of class "TestList"