以將數組添加到棧中爲例,演示棧彈出數據,訪問棧頂元素、判斷棧是否爲空、判斷棧是否滿了
public class MyStack {
// 定義數組的最大長度
private int maxsize;
// 定義一個數組
private long[] arr;
// 定義棧頂
private int top;
// 構造方法
public MyStack(int size) {
maxsize = size;
arr = new long[maxsize];
top = -1;
}
/*
* 添加數據(壓入數據)
*/
public void push(long value) {
arr[++top] = value;
}
/*
* 移除數據(彈出數據)
*/
public long pop() {
return arr[top--];
}
/*
* 訪問棧頂元素
*/
public long peek() {
return arr[top];
}
/*
* 判斷棧是否爲空
*/
public boolean isEmoty() {
return top == -1;
}
/*
* 判斷棧是否滿了
*/
public boolean isFull() {
return top == maxsize - 1;
}
}
寫一個測試類
public class TestMyStack {
public static void main(String[] args) {
MyStack myStack = new MyStack(10);
// 壓入數據
myStack.push(22);
myStack.push(11);
myStack.push(77);
myStack.push(88);
myStack.push(33);
myStack.push(44);
// 訪問棧頂元素
System.out.println(myStack.peek());
// 判斷棧是否爲空
System.out.println("棧是否爲空" + myStack.isEmoty());
// 判斷棧是否滿了
System.out.println("棧是否滿了" + myStack.isFull());
// 彈出數據
while (!myStack.isEmoty()) {
System.out.print(myStack.pop() + " ");
}
}
}
運行結構