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