Java Reference
In-Depth Information
The code above will set the next field at location 4000 to 2000 and set last to 2000 . The following is the result:
2000
top
last
4000
15
4000
36
2000
2000
Now top ( 4000 ) points to the node containing 36 ; this node's next field is 2000 and, hence, points to the node
containing 15 . This node's next field is null , indicating the end of the list. The value of last is 2000 , the address of the
last node in the list.
Program P3.1 reads the numbers and creates the linked list as discussed. To verify that the list has been built
correctly, we should print its contents. The function printList traverses the list from the first node to the last, printing
the number at each node.
Program P3.1
import java.util.*;
public class BuildList1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Node top, np, last = null;
top = null;
System.out.printf("Enter some integers ending with 0\n");
int n = in.nextInt();
while (n != 0) {
np = new Node(n); //create a new node containing n
if (top == null) top = np; //set top if first node
else last.next = np; //set last.next for other nodes
last = np; //update last to new node
n = in.nextInt();
}
System.out.printf("\nThe items in the list are\n");
printList(top);
} //end main
public static void printList(Node top) {
while (top != null) { //as long as there's a node
System.out.printf("%d ", top.num);
top = top.next; //go on to the next node
}
System.out.printf("\n");
} //end printList
} //end class BuildList1
class Node {
int num;
Node next;
 
Search WWH ::




Custom Search