
import java.util.Iterator;

public class Stack<T> implements Iterable<T>
{
	class Node
	{
		T value;
		Node next;
	};

	private Node top;
	private int n;

	Stack()
	{
		top = null;
		n = 0;
	}

	public void push(T value)
	{
		Node x = new Node();
		x.value = value;
		x.next = top;
		top = x;
		n++;
	}

	public T pop()
	{
		T x = top.value;
		top = top.next;
		n--;
		return x;
	}

	public T peek()
	{
		return top.value;
	}

	public boolean empty()
	{
		return top == null;
	}

	public int count()
	{
		return n;
	}

	public Iterator<T> iterator()
	{
		return new ListIterator();
	}

	private class ListIterator implements Iterator<T>
	{
		private Node current;

		public ListIterator()
		{
			current = top;
		}

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

		public T next()
		{
			T value = current.value;
			current = current.next;
			return value;
		}

		public void remove() {}
	}

	public static void main(String[] args)
	{
		Stack<String> s = new Stack<String>();

		s.push("A");
		s.push("B");
		s.push("C");

		for (String p : s)
			System.out.println(p);

		while (!s.empty())
			System.out.println(s.pop());
	}
}
