Tuesday 21 September 2010

LinkedList example in java

This program does the same thing as above using java.util.LinkedList, which hides the linking infrastructure and extra class. It is a doubly-linked list so moving in both directions is possible.


package linkedlistexamples;
import java.util.*;
public class LibraryLinkedList {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
LinkedList lst = new LinkedList();
//... Read and build list of words.
while (in.hasNext()) {
String word = in.next();
lst.add(word);
}
//... Enhanced for loop to print list forward.
// Could also use an Iterator (forward only) or
// ListIterator (forward or backward).
System.out.println("*** Print words in order of entry");
for (String s : lst) {
System.out.println(s);
}
//... Use ListIterator go to backward. Start at end.
System.out.println("*** Print words in reverse order of entry");
for (ListIterator lit = lst.listIterator(lst.size());
lit.hasPrevious();) {
System.out.println(lit.previous());
}
}
}

No comments:

Post a Comment