package OOPLS;

import java.util.Vector;
import java.util.EmptyStackException;

public class LeakyStack<E> {
    Vector<E> elements;
    int n, top, bottom;
    public LeakyStack(int m) {
        this.n = m+1;
        elements = new Vector<E>();
        elements.setSize(n);
        elements.trimToSize();
        top = bottom = 0;
    }
    public E push(E e) {
        top = (top + 1) % n;
        if (top == bottom) bottom = (bottom+1) % n;
        elements.set(top,e);
        return e;
    }
    public E pop() throws EmptyStackException {
        if (empty()) throw new EmptyStackException();
        E rv = elements.get(top);
        top = (top + n - 1) % n;
        return rv;
    }
    public E peek() throws EmptyStackException {
        if (empty()) throw new EmptyStackException();
        return elements.get(top);
    }
    public boolean empty() {
        return top == bottom;
    }
    public int search(Object o) {
        int i = top, ord = 1;
        while (i != bottom) {
            if (elements.get(i).equals(o)) return ord;
            ++ord;
            i = (i+n-1) % n;
        }
        return -1;
    }
}
