/** * A singly linked list. * * @author Josef Nilsen * @version v1.0B */public class LinkedList<T>{ private ListElement<T> first; // First element in list. private ListElement<T> last; // Last element in list. private int size; // Number of elements in list. /** * A list element. */ private static class ListElement<T> { public T data; public ListElement<T> next; public ListElement(T data) { this.data = data; this.next = null; } } /** * Creates an empty list. */ public LinkedList() { } /** * Inserts the given element at the beginning of this list. */ public void addFirst(T element) { if(size==0) { first = new ListElement<T>(element); last = first; } else { ListElement<T> tmp = first; first = new ListElement<T>(element); first.next = tmp; } size++; } /** * Inserts the given element at the end of this list. */ public void addLast(T element) { if(size==0) { first = new ListElement<T>(element); last = first; } else { ListElement<T> tmp = last; last = new ListElement<T>(element); tmp.next = last; } size++; } /** * Returns the first element of this list. * Returns <code>null</code> if the list is empty. */ public T getFirst() { if(size==0) { return null; } else { return first.data; } } /** * Returns the last element of this list. * Returns <code>null</code> if the list is empty. */ public T getLast() { if(size==0) { return null; } else { return last.data; } } /** * Returns the element at the specified position in this list. * Returns <code>null</code> if <code>index</code> is out of bounds. */ public T get(int index) { if(index<size) { ListElement<T> tmp = first; for(int i=0; i<index; i++) { tmp = tmp.next; } return tmp.data; } else { return null; } } /** * Removes and returns the first element from this list. * Returns <code>null</code> if the list is empty. */ public T removeFirst() { if(size==0) { return null; } else { ListElement<T> tmp = first; first = tmp.next; return tmp.data; } } /** * Removes all of the elements from this list. */ public void clear() { first = null; size=0; } /** * Returns the number of elements in this list. */ public int size() { return size; } /** * Returns <code>true</code> if this list contains no elements. */ public boolean isEmpty() { return size == 0; } /** * Returns a string representation of this list. The string * representation consists of a list of the elements enclosed in * square brackets ("[]"). Adjacent elements are separated by the * characters ", " (comma and space). Elements are converted to * strings by the method toString() inherited from Object. */ public String toString() { StringBuffer buffer = new StringBuffer(); ListElement<T> tmp = first; for(int i=0; i<size; i++) { if(tmp.data == null) { buffer.append("[*null*]"); } else { buffer.append("["+tmp.data.toString()+"]"); } if(i!=size-1) { buffer.append(", "); } tmp=tmp.next; } return buffer.toString(); } }