版权声明:Please make the source marked https://blog.csdn.net/qq_31807385/article/details/86484293
题目要求:
如标题
代码实现:
package com.isea.brush;
/**
* 使用数组结构实现固定长度的栈结构
* 实现思路:index位置表示的是如果要入栈,元素应该存放数据的位置
*/
public class ArrayStack {
private Integer data[];
private int index;
public ArrayStack(int initalSize) {
if (initalSize <= 0) {
throw new IllegalArgumentException("The init is less than 0...");
}
data = new Integer[initalSize];
index = 0;
}
public void push(int value) {
if (index == data.length) {
throw new IllegalArgumentException("The stack is full...");
}
data[index++] = value;
}
public int pop() {
if (index == 0) {
throw new IllegalArgumentException("The stack is empty...");
}
return data[--index];
}
public int peek() {
if (index == 0) {
throw new IllegalArgumentException("The stack is empty...");
}
return data[index - 1];
}
}