堆栈
接口·Interface
public interface Stack {
public boolean push(Object obj) throws Exception;//入栈
public Object pop() throws Exception; //出栈
public Object getData() throws Exception; //获取栈顶元素
public int size(); //获取堆栈大小
public boolean isEmpty(); //判断堆栈是否为空
public boolean isFull(); //判断堆栈是否已满
public void clear(); //置空堆栈
}
堆栈的实现
public class SeqStack implements Stack {
private final int defaultSize = 10; //默认大小
private int top; //栈顶数据元素下标
private int maxStackSize; //最大数据元素个数
private Object[] stack; //数组对象
//无参的构造函数
public SeqStack() {
maxStackSize = defaultSize;
stack = new Object[defaultSize];
}
//带参的构造函数
public SeqStack(int size) {
maxStackSize = size;
top = -1;
stack = new Object[size];
}
//压栈
public boolean push(Object obj) throws Exception {
if (!isFull()) { //不满,则执行入栈操作
top++; //产生新栈顶元素
stack[top] = obj; //保存元素
return true;
} else {
System.out.println("堆栈已满!" + obj + "无法入栈");
return false;
}
}
//出栈
public Object pop() throws Exception {
Object ret = null;
if (!isEmpty()) { //栈不空
ret = stack[top]; //设置返回值
stack[top] = null; //将原数据清空
top--; //产生新的栈顶元素
} else {
System.out.println("堆栈为空!");
} //返回栈顶元素
return ret;
}
public Object getData() throws Exception {
Object ret = null;
if (!isEmpty()) { //栈不空
ret = stack[top]; //设置返回值
} else {
System.out.println("堆栈已空!");
}
return ret;
}
public int size() {
return top;
}
//判断堆栈是否为空
public boolean isEmpty() {
return (top == -1);
}
//判断堆栈是否已满
public boolean isFull() {
return (top == maxStackSize - 1);
}
//置空堆栈
public void clear() {
top = -1;
}
}
测试类:
public class Test {
public static void main(String[] args) {
SeqStack stack = new SeqStack();
int a[] = {1, 2, 3, 4, 5, 6};
try {
for (int i = 0; i < a.length; i++) {
stack.push(new Integer(a[i]));
}
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}