Java Reference
In-Depth Information
You should observe that the code works even if the list is initially empty (that is, if top is null ). In this case, it
converts this:
top
np
12
to this:
top
np
12
3.5 Building a Linked List: Adding a New Item at the Head
Consider again the problem of building a linked list of positive integers but, this time, we insert each new number
at the head of the list rather than at the end. The resulting list will have the numbers in reverse order to how they are
given. Suppose the incoming numbers are as follows ( 0 terminates the data):
36 15 52 23 0
We would like to build the following linked list:
top
23
52
15
36
The program to build the list in reverse order is actually simpler than the previous one. It is almost identical to
Program P3.1. The only changes are in the while loop. As each new number is read, we set its link to point to the first
node, and we set top to point to the new node, making it the (new) first node. These changes are incorporated into
Program P3.2, written as class BuildList2 .
Program P3.2
import java.util.*;
public class BuildList2 {
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
np.next = top; //set it to point to first node
top = np; //update top to point to new node
n = in.nextInt();
}
 
 
Search WWH ::




Custom Search