/**
* A single linked list.
*
* @author Josef Nilsen
* @version v1.0B
*/
public class LinkedList<T> implements Stack<T>
{
private ListElement<T> first; // First 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 push(T element) {
if(size==0) {
first = new ListElement<T>(element);
} else {
ListElement<T> tmp = first;
first = new ListElement<T>(element);
first.next = tmp;
}
size++;
}
/**
* Returns the first element of this list.
* Returns <code>null</code> if the list is empty.
*/
public T pop() {
if(size==0) {
return null;
} else {
ListElement<T> tmp = first;
first = tmp.next;
return tmp.data;
}
}
public T top() {
if(size==0) {
return null;
} else {
return first.data;
}
}
/**
* 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;
}
}