MyStack.java类
package com.kami.leetcode.alg_stack; public class MyStack { //栈的底层我们用数组来存储数据 int[] elements; public MyStack(){ elements = new int[0]; } //压入元素 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 < elements.length - 1; 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 ? true : false; } }
testMyStack.java测试类
package com.kami.leetcode.alg_stack.test; import com.kami.leetcode.alg_stack.MyStack; public class testMyStack { public static void main(String[] args) { //创建一个栈 MyStack myStack = new MyStack(); //压入数组 myStack.push(9); myStack.push(7); myStack.push(8); //取出栈顶元素 System.out.println(myStack.pop()); //查看栈顶元素 System.out.println(myStack.peek()); //判断是否为空 System.out.println(myStack.isEmpty()); } }