Java implements simple stack code
- 2020-05-19 04:51:45
- OfStack
This article example for you to share the Java implementation of a simple stack of specific code, 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 the stack
*/
protected int depth = 0;
/**
* The actual stack
*/
protected int[] stack = new int[MAX_DEPTH];
/**
* push To add to the stack 1 An element
*
* @param n Integer to add
*/
protected void push(int n) {
if (depth == MAX_DEPTH - 1) {
throw new RuntimeException(" The stack is full and cannot be added. ");
}
stack[depth++] = n;
}
/**
* pop , returns the top element of the stack and deletes it from the stack
*
* @return The stack elements
*/
protected int pop() {
if (depth == 0) {
throw new RuntimeException(" The stack element has been removed and cannot be retrieved. ");
}
// --depth . dept Minus the first 1 Assign the value to the variable dept , so the depth of the whole stack is reduced 1 Is removed from the stack.
return stack[--depth];
}
/**
* peek , returns the top element of the stack without removing it from the stack
*
* @return
*/
protected int peek() {
if (depth == 0) {
throw new RuntimeException(" The stack element has been removed and cannot be retrieved. ");
}
return stack[depth - 1];
}
}