stack.java

来自「国外的数据结构与算法分析用书」· Java 代码 · 共 48 行

JAVA
48
字号
/**	A simple bounded stack class used to demonstrate programmer-defined exceptions.
	Some methods throw subclasses of Exception that must be caught, and others throw
	subclasses of RuntimeException that don't need to be caught. */
public class Stack
{
	protected int index = 0;
	protected Object[] array;

	/**	Creates a stack with a capacity of `size'. */
	public Stack(int size)
	{
		array = new Object[size];
	}

	/**	Returns the top element in the stack. */
	public Object top() throws IllegalTopException
	{
		if (index == 0)
			throw new IllegalTopException("No item to return");
		return array[index - 1];
	}

	/**	Push a new element onto the stack. */
	public void push(Object obj)
	{
		if (index == array.length)
			throw new StackFullException("Can't push onto a full stack");
		array[index++] = obj;
	}

	/**	Remove the top element from the stack. */
	public void pop()
	{
		if (index == 0)
			throw new IllegalPopException("No item to pop");
		index--;
	}

	/**	Returns a string with the contents of the stack. */
	public String toString()
	{
		String result = new String();
		for (int i = 0; i < index; i++)
			result += array[i].toString() + "\n";
		return result;
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?