package dm0;
public class StackTest {
public static void main(String[] args) { //throws Exception 在main函数中抛出就会交给虚拟机处理,会停止程序;
//在普通函数中抛出就会给上一级处理
Stack stack = new Stack(3);
try {
stack.push(new String("1"));
stack.push(new String("2"));
stack.push(new String("3"));
stack.push(new String("4")); //抛出异常
} catch (Exception e) { //catch接到异常后会继续向下执行,不会将程序停止
e.printStackTrace();
}
try {
System.out.println(stack.peek());
} catch (Exception e) {
e.printStackTrace();
}
while (stack.getStackPosition() >= 0) {
try {
System.out.println(stack.pop());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class Stack {
Object[] data;
int maxSize; // 最大个数
int top; // 栈顶位置
// 构造函数
public Stack(int maxSize) {
this.maxSize = maxSize;
data = new Object[maxSize];
top = -1;
}
// 堆栈长度
public int getSize() {
return maxSize;
}
// 返回堆栈元素位置
public int getStackPosition() {
return top;
}
// 判断堆栈是否为空
public boolean isEmpty() {
return top == -1;
}
// 判断栈是否满了,放时看满不满
public boolean isFull() {
return top + 1 == maxSize;
}
public boolean push(Object data) throws Exception {
if (isFull()) {
throw new Exception("栈已满");
}
this.data[++top] = data; // top是从-1加上来的,所以永远指向元素的位置
return true;
}
// 从栈中取数据,取时看空不空
public Object pop() throws Exception {
if (isEmpty()) {
throw new Exception("栈已空");
}
return this.data[top--];
}
// 返回栈顶元素,但是不取出
public Object peek() throws Exception {
if (isEmpty()) {
throw new Exception("栈已空");
}
return this.data[getStackPosition()];
}
}
Stack实现
最新推荐文章于 2024-06-26 21:08:25 发布