【Java实现栈】压栈,弹栈,扩容,降容...

import java.util.Arrays;

/**
 * @Description: 手动实现栈  压栈 弹栈 判空 判满
 *
 *                             top=1  2
 *   top=-1       top=0 1      top=0  1
 * @Author: juwei
 * @Date: 2021/3/1 19:12
 * @Version: 1.0
 *
 */
public class MyStack {
	private int top;   //栈顶
	private int[] array;  //栈
	private int capacity; //容量

	/**
	 * 初始化
	 * @param initCapacity
	 */
	MyStack(int initCapacity) {
		if (initCapacity > 0) {
			this.array = new int[initCapacity];
			capacity = initCapacity;
			top = -1;
		} else if (initCapacity == 0) {
			this.array = new int[0];
		} else {
			throw new IllegalArgumentException("Illegal param: " + initCapacity);
		}
	}

	/**
	 * 压栈
	 * @param x
	 */
	public void push(int x) {
		if (isFull()) {
			System.out.println("栈溢出...");
			// System.exit(1); 准备扩容,扩容因子可以自己指定
			System.out.println("ready resize...");
			resize(2);
		}
		array[++top] = x;
		System.out.println("压栈: " + x);
	}

	/**
	 * 弹栈, 
	 * @return
	 */
	public int pop() {
		if (isEmpty()) {
			System.out.println("栈是空的...");
			System.exit(1);
		} else if (top < (capacity >> 1)) {
	    	// 当前栈顶小于容量的一半时,降容
			downSize(1);
		}
		return array[top--];

	}

	/**
	 * 判满
	 * @return
	 */
	public boolean isFull() {
		return top == capacity - 1;
	}

	/**
	 * 判空
	 * @return
	 */
	public boolean isEmpty() {
		return top == -1;
	}

	/**
	 * 栈大小
	 * @return
	 */
	public int size() {
		return top + 1;
	}

	/**
	 * 扩容
	 */
	public void resize(int loadFactor) {
		System.out.println("扩容前容量:" + this.array.length+ "," + Arrays.toString(array));
		capacity = capacity * loadFactor;
		this.array = Arrays.copyOf(array, capacity);
		System.out.println("扩容后容量:" + this.array.length+ "," + Arrays.toString(array));
	}

	/**
	 * 降容(2倍降)
	 */
	public void downSize(int loadFactor) {
		System.out.println("降容前容量:" + this.array.length + "," + Arrays.toString(array));
		capacity = capacity >> loadFactor;
		this.array = Arrays.copyOf(array, capacity);
		System.out.println("降容后容量:" + this.array.length + "," + Arrays.toString(array));
	}

	/**
	 * 打印栈内容
	 */
	public void printMyStack() {
		for (int i = 0; i < top; i++) {
			System.out.print(array[i] + ",");
		}
	}

	public static void main(String[] args) {
		// 初始化
		MyStack myStack = new MyStack(5);

		myStack.push(5);
		myStack.push(6);
		myStack.push(7);
		System.out.println(myStack.size());
		myStack.push(8);
		myStack.push(9);
		myStack.push(10);
		myStack.push(11);
		myStack.push(12);
		myStack.push(13);
		myStack.push(14);
		myStack.pop();
		myStack.pop();
		myStack.pop();
		myStack.pop();
		myStack.pop();
		myStack.pop();
	}

}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值