arraystack.java

来自「真的很麻烦也」· Java 代码 · 共 95 行

JAVA
95 行
字号
interface Stack
{
	public int size();
	public boolean isEmpty();
	public Object top() throws StackEmptyException;
	public Object push (Object element);
	public Object pop() throws StackEmptyException;
	
	
}
class StackEmptyException extends RuntimeException
{
	public StackEmptyException(String err)
	{
		super(err);
	}
}
class StackFullException extends RuntimeException
{
	public StackFullException(String err)
	{
		super(err);
	}
}
public class ArrayStack implements Stack
{
	public static final int CAPACITY = 1000;
	private int capacity;
	private Object S[];
	private int top = -1;
	public ArrayStack()
	{
		this(CAPACITY);
	}
	public ArrayStack(int cap)
	{
		capacity = cap;
		S = new Object[capacity];
			
	}
	
	public int size()
	{
		return (top +1);
	}
	public boolean isEmpty()
	{
		return (top<0);
	}
	
	public Object push(Object obj) //throws StackFullException
	{
		if (size()==capacity)
		//throw new StackFullException("Stack overflow.");
		{
			return ("Stack overflow.");
		}
		S[++top] = obj;
		return ("-");
	}
	public Object top()// throws StackEmptyException
	{
		if (isEmpty())
		{
			return ("Stack is empty.");
		}
		//throw new StackEmptyException("Stack is empty.");
		return S[top];
	}
	
	public Object pop()// throws StackEmptyException
	{
		Object elem;
		if (isEmpty())
		{
			return ("Stack is empty.");
		}
//		throw new StackEmptyException("Stack is Empty.");	
		elem = S[top];
		S[top--] = null;
		return elem;
	}
	
	public String getContent()
	{
		String cont= "";
		for (int i =0; i<=top; i++ )
		{
			cont += (S[i].toString()+ ",");
		}
		if (cont != "")
			return (cont.substring(0,cont.length()-1));
		else return cont;
	}
}

⌨️ 快捷键说明

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