package stack;

/**
 * Linked List based Stack
 * @author Winston Prakash
 */
public class LinkedListStack<E> implements Stack<E>{
    
    Entry<E> header = new Entry<E>(null, null);
    
    public boolean empty() {
        return header.next == null;
    }
    
    public E peek() {
        if (empty()){
            throw new EmptyStackException();
        }
        return header.next.element;
    }
    
    public void push(E item) {
        Entry<E> newEntry = new Entry<E>(item, header.next);
        header.next = newEntry;
    }
    
    public E pop() {
        E element = peek();
        header.next = header.next.next;
        return element;
    }
    
    public int search(E item) {
        if (empty()){
            throw new EmptyStackException();
        } 
        int count = 0;
        Entry<E> entry =  header.next;
        while (entry != null){
            count++;
            if (entry.element == item){
                return count; 
            }
            entry = entry.next;
        }
        return -1;
    }
    
    
    private static class Entry<E>{
        E element;
        Entry<E> next;
        Entry(E element, Entry<E> next){
            this.element = element;
            this.next = next;
        }
    }
}