arraystack.java

来自「这里面包含有栈」· Java 代码 · 共 64 行

JAVA
64
字号
package org.huhuiyu.datastructures;

public class ArrayStack {
	private Object[] datas;
	private int count = 0;

	public ArrayStack(int size) {
		datas = new Object[size];
	}

	public void push(Object data) {
		// 添加到数组的最后索引位置
		if (count == datas.length) {
			throw new IllegalStateException("堆栈已满!");
		}
		datas[count] = data;
		count++;
	}

	public Object pop() {
		if (isEmpty()) {
			throw new IllegalStateException("堆栈为空!");
		}
		count--; // 返回最后一笔数据
		return datas[count];
	}

	public Object peek() {
		if (isEmpty()) {
			throw new IllegalStateException("堆栈为空!");
		}
		return datas[count - 1]; // 返回最后一笔数据
	}

	public void clear() {
		datas = new Object[datas.length];
		count = 0;
	}

	public boolean isEmpty() {
		return count == 0;
	}

	public int size() {
		return count;
	}

	public int capacity() {
		return datas.length;
	}

	public static void main(String[] args) {
		ArrayStack stack = new ArrayStack(10);
		for (int i = 1; i <= stack.capacity(); i++) {
			stack.push(i);
		}
		System.out.println("size():" + stack.size());
		while (!stack.isEmpty()) {
			System.out.println(stack.pop());
		}
		System.out.println("size():" + stack.size());
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?