package lista;
import java.util.Enumeration;
public class Lista {
	protected NodoLista tope;
	
	public Lista() {
		tope = null;
	}
	
	public boolean isEmpty() {
		return (tope == null);
	}
	
	public void addFirst(Object o) {
		NodoLista nli = new NodoLista(o,tope);
		tope = nli;
	}
	
	public void add(Object o) {
		addFirst(o);
	}
	
	public void addLast(Object o) {
		NodoLista ndl = tope;
		while (ndl.sig != null)
			ndl=ndl.sig;
		ndl.sig =new NodoLista(o,null);
	}
	
	public Object getFirst() throws EmptyListaException {
		Object res=null;
                try {
			res = tope.dato;
                } catch (NullPointerException e) {
                        throw new EmptyListaException("getFirst: Lista vacia");
                }
		return res;
	}
	
	public Object getLast() throws EmptyListaException {
		Object res=null;
                try {
			NodoLista ndl = tope;
			while (ndl.sig != null)
				ndl = ndl.sig;
			res = ndl.dato;
                } catch (NullPointerException e) {
			throw new EmptyListaException("getLast: Lista vacia");
                }
		return res;
	}
	
	public Object removeFirst() throws EmptyListaException {
		Object res=null;
                try {
			NodoLista ndl = tope;
			tope = tope.sig;
			res = ndl.dato;  
			// En C++ habria que devolver ndl
                }
                catch (NullPointerException e) {
                        throw new EmptyListaException("removeFirts: Lista vacia");
                }
		return res;
	}
		
	public Object removeLast() throws EmptyListaException {
		Object res=null;
                try {
			NodoLista ndl = tope;
			if (ndl.sig==null) {
				tope = null;
				res = ndl.dato;
				// En C++ habria que devolver ndl
			} else {
				while (ndl.sig.sig != null)
					ndl = ndl.sig;
				NodoLista ondl = ndl.sig;
				ndl.sig =null;
				res = ondl.dato;
				// En C++ habria que devolver ondl
			}			
                } catch (NullPointerException e) {
                        throw new EmptyListaException("removeLast: Lista vacia");
                }
		return res;
	}
	
	public Enumeration elements() {
		return new ListaEnum(tope);
	}
	
	public String toString() {
		NodoLista ndl = tope;
		String s = "Lista(";
		while (ndl!=null) {
			s += ndl.dato +" ";
			ndl=ndl.sig;
		}
		s += ")";
		return s;
	}		 

}
		
class NodoLista {
	protected Object dato;
	protected NodoLista sig;
	public NodoLista(Object o, NodoLista s) {
		dato = o;
		sig = s;
	}
}

class ListaEnum implements Enumeration {
	NodoLista nodo;
	public ListaEnum(NodoLista n) {
		nodo = n;
	}
	
	public boolean hasMoreElements() {
		return nodo!=null;
	}
	
	public Object nextElement() {
		Object res = nodo.dato;
		nodo = nodo.sig;
		return res;
	}
}
		
