import java.util.Iterator;
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
// Create a new LinkedList
LinkedList<Integer> list = new LinkedList<Integer>();
// Add Items to the array list
list.add(new Integer(1));
list.add(new Integer(2));
list.add(new Integer(3));
list.add(new Integer(4));
list.add(new Integer(5));
list.add(new Integer(6));
list.add(new Integer(7));
list.add(new Integer(8));
list.add(new Integer(9));
list.add(new Integer(10));
// Use iterator to display the values
for (Iterator i = list.iterator(); i.hasNext();) {
Integer integer = (Integer) i.next();
System.out.println(integer);
}
// Remove the element at index 5 (value=6)
list.remove(5);
// Set the value at index 5, this overwrites the value 7
list.set(5, new Integer(66));
// Use the linked list as a queue:
// add an object to the end of the list (queue)
// remove an item from the head of the list (queue)
list.addLast(new Integer(11));
Integer head = (Integer) list.removeFirst();
System.out.println("Head: " + head);
// Use iterator to display the values
for (Iterator i = list.iterator(); i.hasNext();) {
Integer integer = (Integer) i.next();
System.out.println(integer);
}
}
}
|