<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">/*
   Stack.java

   Copyright (C) 2004 Wojciech Polak.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library 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
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

import java.util.Iterator;

public class Stack
{
    Node top = null;
    int size = 0;

    public void push (Object o) {
	Node node = new Node (o, top);
	top = node;
	size++;
    }

    public Object pop () throws Exception {
	if (top != null) {
	    Object t = top.item;
	    top = top.next;
	    size--;
	    return t;
	}
	else {
	    throw new Exception ("Empty stack!");
	}
    }
    
    public void clear () {
	top = null;
	size = 0;
    }
    
    public boolean empty () {
	return (top == null);
    }

    public Object peek () {
	return top.item;
    }

    public int size () {
	return size;
    }

    private class Node
    {
	public Node next;
	public Object item;
	
	public Node (Object o, Node n) {
	    next = n;
	    item = o;
	}
    }

    // Implements Iterator

    public Iterator iterator () {
	return new StackIterator ();
    }

    private class StackIterator implements Iterator
    {
	private Node curr, next;

	StackIterator () {
	    next = top;
	}

	public boolean hasNext () {
	    return (next != null);
	}

	public Object next () {
	    curr = next;
	    next = next.next;
	    return curr.item;
	}

	public void remove () {
	    throw new UnsupportedOperationException ();
	}
    }
}

</pre></body></html>