Java Reference
In-Depth Information
If LL is a LinkedList , we can use it as follows:
LL.addInPlace(new NodeData(25));
This will create a Node with a NodeData object containing 25 and insert this node in the list so that the list is in
ascending order.
Program P3.4 reads integers, builds a linked list in ascending order, and prints the sorted list. You will observe
that we have dropped the word public from the classes NodeData , Node , and LinkedList . This is merely to allow
us to store the entire program in one file, which must be called LinkedListTest.java since the name of the public
class is LinkedListTest . Recall that Java requires that a file contain only one public class. We will elaborate on this in
Section 3.9.
Program P3.4
import java.util.*;
public class LinkedListTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
LinkedList LL = new LinkedList();
System.out.printf("Enter some integers ending with 0\n");
int n = in.nextInt();
while (n != 0) {
LL.addInPlace(new NodeData(n));
n = in.nextInt();
}
LL.printList();
} //end main
} //end LinkedListTest
class NodeData {
int num;
public NodeData(int n) {
num = n;
}
public int compareTo(NodeData nd) {
if (this.num == nd.num) return 0;
if (this.num < nd.num) return -1;
return 1;
} //end compareTo
public String toString() {
return num + " ";
//" " needed to convert num to a string; may also use "" (empty string)
}
} //end class NodeData
class Node {
NodeData data;
Node next;
Search WWH ::




Custom Search