JAVA实现简单的堆栈结构

package Stack;

public class Stack<E> {// 不知道栈中要存入什么类型,用泛型

	/**
	 * @param PLA
	 *  JAVA实现简单堆栈
	 */
	private Object[] stack;// java不支持泛型数组(可以用其它容器来使用)
	private int index;// 充当指针
	private static final int SIZE = 5;// 默认栈的初始大小

	// 默认构造器
	public Stack() {
		stack = new Object[SIZE];
		index = -1;
	}

	// 带参数的构造器
	public Stack(int size) {
		if (size < 0) {
			System.out.println("所输入的栈的大小不合法");
			throw new IllegalArgumentException();
		}
		stack = new Object[size];
		index = -1;
	}

	// 入栈操作
	public synchronized void push(E data) {
		if (isFull()) {// 若栈满了,创建一个新栈,容量为当前栈的两倍
			Object[] temp = stack;
			stack = new Object[temp.length * 2];
			System.arraycopy(temp, 0, stack, 0, temp.length);
			System.out.println("当前栈已满,已创建新栈,容量扩充一倍");
		}
		stack[++index] = data;
	}

	// 出栈操作
	public synchronized E poll() {
		if (!isEmpty()) {
			E temp = getTop();
			stack[index--] = null;
			return temp;
		}
		return null;
	}

	// 获取栈顶对象
	public E getTop() {
		return (E) stack[index];
	}

	public boolean isFull() {
		return index >= stack.length - 1;
	}

	public boolean isEmpty() {
		return index == -1;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		/*
		 * Stack<Integer> s = new Stack<Integer>(3); s.push(2); s.push(4);
		 * s.push(6); System.out.println(s.poll());
		 * System.out.println(s.poll()); System.out.println(s.poll());
		 * System.out.println(s.poll());
		 */
		Stack<String> s = new Stack<String>(3);
		s.push("哈哈1");
		s.push("哈哈2");
		s.push("哈哈3");
		s.push("哈哈4");
		System.out.println(s.poll());
		System.out.println(s.poll());
		System.out.println(s.poll());
		System.out.println(s.poll());
		System.out.println(s.poll());
	}

}

运行结果:

当前栈已满,已创建新栈,容量扩充一倍
哈哈4
哈哈3
哈哈2
哈哈1
null


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值