特点:先进后出,后进先出
创建初始化类
public class MyStack {
int[] elements;
public MyStack() {
elements = new int[0];
}
public void showStack() {
System.out.println("栈中所有元素:"+Arrays.toString(elements));
}
}
栈的相关操作
压栈
public void push(int element) {
//创建一个新数组
int[] newArr = new int[elements.length+1];
for (int i = 0; i < elements.length; i++) {
newArr[i] = elements[i];
}
//把新元素添加进数组中
newArr[elements.length] = element;
//把新数组赋给原来的数组
elements = newArr;
}
弹栈(取出栈顶元素)
public int pop() {
//判断栈中是否有元素
if(elements.length == 0) {
throw new RuntimeException("Stack is empty");
}
int element = elements[elements.length-1];
//创建一个新数组用来替换原来的数组(因为弹栈之后数组长度要改变)
int[] newArr = new int[elements.length-1];
for (int i = 0; i < newArr.length; i++) {
newArr[i] = elements[i];
}
//把新数组赋给原来的数组
elements = newArr;
return element;
}
查看栈顶元素(不弹出)
public int peek() {
//栈中没有元素
if(elements.length==0) {
throw new RuntimeException("stack is empty");
}
return elements[elements.length-1];
}
判断栈是否为空
public boolean isEmpty() {
return elements.length==0;
}
测试
public class TestMyStack {
public static void main(String[] args) {
MyStack myStack = new MyStack();
//向栈中压入三个元素
myStack.push(33);
myStack.push(44);
myStack.push(55);
myStack.showStack(); //查看栈中所有元素
System.out.println("取出栈顶元素:"+ myStack.pop());
System.out.println("取出栈顶元素:"+ myStack.pop());
myStack.showStack(); //查看栈中所有元素
}
}