用数组的方式实现
public class ArrayStack {
private long[] array; //数组方式实现
private int top; //栈顶
private int size; //栈内元素个数
public ArrayStack(int maxsize) { //初始化
size = maxsize;
array = new long[size];
top = -1;
}
public long peek() { //返回栈顶元素
if (isEmpty()) {
throw new RuntimeException("栈为空!");
} else {
System.out.println("栈顶元素为:" + array[top]);
return array[top];
}
}
public void push(long elem) { //入栈
if (isFull()) {
throw new RuntimeException("栈已满!");
}
array[++top] = elem;
System.out.println("栈中成功插入元素,该元素为:" + elem);
}
public void pop() { //出栈
if (isEmpty()) {
throw new RuntimeException("栈为空!");
}
System.out.println("栈中元素成功被删除,该元素为:" + array[top]);
top--;
}
public int size() { //栈的元素个数
return size;
}
public boolean isEmpty() { //栈是否为空
return top == -1;
}
public boolean isFull() { //栈是否已满
return top == size - 1;
}
}
原文:https://www.cnblogs.com/kwdlh/p/13956527.html