The stack is one of the most important data structures in the Java language. Its implementation should at least include the following methods:
1. pop() pop operation, pop the top element of the stack.
2.push(E e) push operation
3.peek() View the top element of the stack
4.isEmpty() Is the stack empty?
In addition, when implementing a stack, several issues should be considered:
1. The initial size of the stack and how to add new stack space after the stack is full
2. Synchronization is required when updating the stack
A simple example, using an array to implement a stack, the code is as follows:
Copy the code code as follows:
public class Stack<E> {
// Java does not support generic arrays. If you need to use them, please use the container provided by Java.
private Object[] stack;
//Default initial size of the stack
private static final int INIT_SIZE = 2;
//Stack top index
private int index;
publicStack() {
stack = new Object[INIT_SIZE];
index = -1;
}
/**
*Construction method
*
* @param initSize
* Initial size of the stack
*/
public Stack(int initSize) {
if (initSize < 0) {
throw new IllegalArgumentException();
}
stack = new Object[initSize];
index = -1;
}
/**
* Pop operation
*
* @return stack top object
*/
public synchronized E pop() {
if (!isEmpty()) {
E temp = peek();
stack[index--] = null;
return temp;
}
return null;
}
/**
* Push operation
*
* @param obj
* Object waiting to be pushed onto the stack
*/
public synchronized void push(E obj) {
if (isFull()) {
Object[] temp = stack;
// If the stack is full, create a stack with twice the current stack space
stack = new Object[2 * stack.length];
System.arraycopy(temp, 0, stack, 0, temp.length);
}
stack[++index] = obj;
}
/**
* View the top object on the stack
*
* @return stack top object
*/
public E peek() {
if (!isEmpty()) {
return (E) stack[index];
}
return null;
}
/**
* Check if the stack is empty
*
* @return Returns true if the stack is empty, otherwise returns false
*/
public boolean isEmpty() {
return index == -1;
}
/**
* Check if the stack is full
*
* @return Returns true if the stack is full, otherwise returns false
*/
public boolean isFull() {
return index >= stack.length - 1;
}
}
Finally, the data structure of the stack (java.util.Stack) is implemented in Java. It is implemented by inheriting the Vector class. Under normal circumstances, we can just use it directly.