This example shares the specific code of Java implementation simple stack for your reference. The specific content is as follows
/** * Created by Frank */public class ToyStack { /** * Maximum depth of stack**/ protected int MAX_DEPTH = 10; /** * Current depth of stack*/ protected int depth = 0; /** * actual stack*/ protected int[] stack = new int[MAX_DEPTH]; /** * push, add an element to the stack* * @param n Integer to be added*/ protected void push(int n) { if (depth == MAX_DEPTH - 1) { throw new RuntimeException("The stack is full, no more elements can be added."); } stack[depth++] = n; } /** * pop, return to the top element of the stack and delete from the stack * * @return The top element of the stack */ protected int pop() { if (depth == 0) { throw new RuntimeException("The elements in the stack have been taken, no more elements can be taken."); } // --depth, dept first subtract 1 and then assign it to the variable dept, so that the depth of the entire stack is reduced by 1 (equivalent to deleting from the stack). return stack[--depth]; } /** * peek, return the element on the top of the stack but not delete it from the stack * * @return */ protected int peek() { if (depth == 0) { throw new RuntimeException("The element in the stack has been taken, and it cannot be taken again."); } return stack[depth - 1]; }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.