?? arraystack.java
字號:
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 + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -