/* dIntProg Browser. A webbrowser written in Java.
 * Copyright (C) 2001 Martin Geisler <gimpster@gimpster.com>
 *  
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the
 * 
 * Free Software Foundation, Inc.,
 * 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/** Stack implements a stack of non-<code>null</code> objects. The
 *  stack is implemented as a conslist. */
public class Stack {
    
    private StackObject s;
    private int size;
    
    /** Constructs the empty stack. */
    public Stack() { 
	s = null;
        size = 0;
    }
    
    /** Adds an object to the stack.
     *  @param obj the object that will be pushed onto the stack. */
    public void push(Object obj) { 
	if (obj != null) {
	    s = new StackObject(obj,s);
            size = size + 1;
        }
    }
    
    /** Removes the object at the top of the stack.
     *  @return The object at the top of the stack, or
     *  <code>null</code> if the stack is empty. */
    public Object pop() {
	if (s == null) 
	    return null;
	Object obj = s.obj;
	s = s.next;
        size = size - 1;
	return obj;
    }

    /** Peeks at the object at the top of the stack without removing
     *  it.
     *  @return The object at the top of the stack, or
     *  <code>null</code> if the stack is empty. */
    public Object peek() {
	if (s == null) { 
	    return null;
        } else {
            return s.obj;
        }
    }

    /** Reports if the stack is empty.
     *  @return <code>true</code> if the stack is empty,
     *  <code>false</code> otherwise. */
    public boolean empty() { 
	return (s == null);
    }

    /** The number of elements on the stack.
     *  @return the number of elements on the stack. */
    public int size() {
        return size;
    }

    /** Clears the stack. */
    public void clear() {
        s = null;
        size = 0;
    }
    
    
    /** Represents a single object on the stack. */
    private class StackObject {
	Object obj;
	StackObject next;
	
	/** Constructor.
	 *  @param obj The object that is to be put onto the stack.
	 *  @param next The former top of the stack. */
	StackObject(Object obj, StackObject next) {
	    this.obj = obj;
	    this.next = next;
	}
    }

}