学习参考
【栈】
import java.util.*;
// 2022-12-15
// 栈:先进后出
class MyStack {
public int[] elem;
public int useSize;
public MyStack(){
this.elem = new int[10];
}
// 是否栈满
public boolean isFull(){
if (this.useSize == this.elem.length){
return true;
}
return false;
}
public void push(int item){
if (isFull()){
this.elem = Arrays.copyOf(this.elem, 2*2*this.elem.length);
}
this.elem[useSize] = item;
this.useSize++;
}
public boolean empty(){
if (this.useSize == 0) return true;
return false;
}
// 弹出栈顶的值, 删除元素
public int pop(){
if (empty()){
throw new RuntimeException("栈空了");
}
int val = this.elem[this.useSize - 1]; // 先进后出 pop输出最后一个
this.useSize--;
return val;
}
// 弹出栈顶的值, 不删除原来的栈元素
public int peek(){
if (empty()){
throw new RuntimeException("栈空了");
}
return this.elem[this.useSize - 1];
}
}
public class Main{
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6};
MyStack myStack = new MyStack();
myStack.elem = arr;
myStack.useSize = 6;
myStack.pop();
}
}