Java数组实现栈
程序员文章站
2022-07-10 20:29:23
...
Java实现数据结构栈可以基于数组实现,基本代码如下:
public class Stack {
//栈底层使用数组
int[] elements;
//初始化栈
public Stack() {
elements = new int[0];
}
//压栈
public void push(int num) {
int[] newArray = new int[elements.length + 1];
for(int i = 0; i < elements.length; i++) {
newArray[i] = elements[i];
}
newArray[elements.length] = num;
elements = newArray;
}
//出栈
public int pop() {
if (elements.length == 0 || elements == null)
throw new RuntimeException("栈为空");
int element = elements[elements.length - 1];
int[] newArray = new int[elements.length - 1];
for(int i = 0; i < elements.length - 1; i++) {
newArray[i] = elements[i];
}
elements = newArray;
return element;
}
//查看栈顶元素
public int peek() {
if (elements.length == 0 || elements == null)
throw new RuntimeException("栈为空");
return elements[elements.length - 1];
}
//判断栈是否为空
public boolean isEmpty() {
return elements.length == 0;
}
}
当然,Java拥有自己的栈类库,存在于Java.util.Stack中。
上一篇: redis的HyperLogLog实战
下一篇: Java代码实现顺序栈和链式栈