Stack实现

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()];
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值