Java classic instance: implements a simple stack, java classic instance Stack
A Stack is a common data structure that complies with the First In Last Out principle and is usually used to implement the reverse order of Object Storage. The basic stack operations include push (add to stack), pop (delete from Stack), and peek (Check the top element of stack and do not delete it ).
/*** Created by Frank */public class ToyStack {/*** maximum stack depth **/protected int MAX_DEPTH = 10; /*** current stack depth */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 and no more elements can be added. ");} Stack [depth ++] = n;}/*** pop, return the stack top element and delete ** @ return stack top element */protected int pop () {if (depth = 0) from the stack) {throw new RuntimeException ("the elements in the stack have been obtained and cannot be retrieved. ");} // -- Depth, dept first subtract 1 and then assign the value 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, returns the top element of the stack but does not delete ** @ return */protected int peek () from the stack () {if (depth = 0) {throw new RuntimeException ("the element in the stack has been obtained and cannot be retrieved. ") ;}Return stack [depth-1] ;}}