您当前的位置: 首页 > 
  • 0浏览

    0关注

    674博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

自己实现栈

沙漠一只雕得儿得儿 发布时间:2016-11-20 14:50:26 ,浏览量:0

package 栈与队列上;

public class MiniStack {
	private int size;							//size是栈顶指针
	private Object[] array = new Object[4];		//Java不能初始化泛型数组,如果需要,则要使用Java反射实现
	/**
	 * 判断数组是否为空
	 * @return
	 */
	public boolean isEmpty() {
		return size == 0 ? true : false;
	}
	/**
	 * 获取栈的大小
	 * @return
	 */
	public int size() {
		return size;
	}
	/**
	 * 数组扩容
	 */
	public void expandCapacity() {
		Object[] newArray = new Object[size * 2];		//扩容为原数组的2倍
		System.arraycopy(array, 0, newArray, 0, size);	//数组复制
		array = newArray;								//指向新的数组,原来的数组被垃圾回收器回收掉
	}
	/**
	 * push操作
	 * @param t
	 */
	public void push(Object t) {
		array[size] = t;		
		size++;					//栈顶指针
		if (size == array.length) {
			expandCapacity();
		}
	}
	/**
	 * 返回栈顶元素
	 * @return
	 */
	public Object peek() {
		if (isEmpty()) {
			return null;
		} else {
			return array[size - 1];
		}
	}
	/**
	 * 弹栈操作
	 * @return
	 */
	public Object pop() {
		if (isEmpty()) {
			return null;
		} else {
			Object t = peek();
			array[size - 1] = null;		//防止内存泄露
			size--;
			return t;
		}
	}
	
	public static void main(String[] args) {
		MiniStack stack = new MiniStack();
		stack.push(1);
		stack.push(2);
		stack.push(3);
		System.out.println("stack is empty ? It`s " + stack.isEmpty());
		System.out.println("stack`s size "+stack.size);
		while (!stack.isEmpty()) {
			System.out.println("pop " + stack.pop());
		}
		System.out.println("stack is empty ? It`s " + stack.isEmpty());
		System.out.println("stack`s size "+stack.size);
	}
}

关注
打赏
1657159701
查看更多评论
立即登录/注册

微信扫码登录

0.0389s