/**
* 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) {
first = new ListElement(element);
}
/**
* Inserts the given element at the end of this list.
*/
public void addLast(T element) {
last = new ListElement(element);
}
/**
* 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;
}
}
/**
* 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;
}
}
/**
* 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) {
for(int i=0; i<index; i++)
{
T match = ListElement.next;
}
return match;
} 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 {
T tmp = first;
first = ListElement.next;
return tmp;
}
/**
* 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() {
return null;
}
}