本文的代码来自于《数据结构与算法(JAVA语言版)》,是笔者在网上找到的资料,非正式出刊版物。笔者对代码一些比较难以理解的部分添加了注释和图解,欢迎大家来讨论。
public class StackArray implements Stack {
private final int LEN = 4; //数组的默认大小
private Object[] elements; //数据元素数组
private int top; //栈顶指针
public StackArray() {
top = -1;
elements = new Object[LEN];
}
public int getSize() {
return top+1;
}//返回堆栈的大小
public boolean isEmpty() {
return top<0;
}//判断堆栈是否为空
public void push(Object e) {
if (getSize()>=elements.length) expandSpace();
elements[++top] = e;
}//数据元素e入栈
private void expandSpace(){
Object[] a = new Object[elements.length*2];
for (int i=0; i<elements.length; i++)
a[i] = elements[i];
elements = a;
}
public Object pop() throws StackEmptyException {
if (getSize()<1)
throw new StackEmptyException("错误,堆栈为空。");
Object obj = elements[top];
elements[top--] = null;
return obj;
}//栈顶元素出栈
public Object peek() throws StackEmptyException {
if (getSize()<1)
throw new StackEmptyException("错误,堆栈为空。");
return elements[top];
}//取栈顶元素
}
public interface Stack {
//返回堆栈的大小
public int getSize();
//判断堆栈是否为空
public boolean isEmpty();
//数据元素e入栈
public void push(Object e);
//栈顶元素出栈
public Object pop() throws StackEmptyException;
//取栈顶元素
public Object peek() throws StackEmptyException;
}
package dsa.exception;
//堆栈为空时出栈或取栈顶元素抛出此异常
public class StackEmptyException extends RuntimeException{
public StackEmptyException(String err) {
super(err);
}
}