[Java]
Public class MyStack <E> {
Private Object [] elements; // declares an object-type array.
Private int size; // the actual number of elements in the array
Public MyStack (){
Elements = new Object [10]; // The initial length is 10.
}
// Check whether the stack is empty
Public boolean empty (){
Return size = 0; // if the number of elements is 0, true is returned. Otherwise, false is returned.
}
// View objects at the top of the stack
Public E peek (){
// If no element is returned, null is returned.
If (empty ()){
Return null;
}
// If an element exists, the last one is returned.
Return (E) elements [size-1];
}
// Remove the object at the top of the stack
Public E pop (){
E e = peek (); // get the backup of the last element
Elements [size-1] = null; // assign a null value to the last element of the array
Size --; // The number of elements minus 1
Return e;
}
// Press the item to the top of the stack.
Public E push (E item ){
EnsureCapacity (size + 1); // check the capacity
Elements [size ++] = item; // Save the imported elements. The number of elements increases by 1.
Return item;
}
// Check whether the capacity is sufficient. If the capacity is insufficient, create a new array based on the original array.
Private void ensureCapacity (int size ){
Int len = elements. length; // obtain the current length of the array.
If (size> len ){
Int newLen = (len * 3)/2 + 1; // the size of each array Expansion
Elements = Arrays. copyOf (elements, newLen );
}
}
// Return the position of the object in the stack, based on 1
Public int search (Object o ){
Int index = lastIndexOf (o); // obtain the subscript of the element in the array.
Return index =-1? Index: size-index;
}
// Method for searching the lower mark
Private int lastIndexOf (Object o ){
If (empty ()){
Throw new EmptyStackException (); // If the array is empty, a custom exception is thrown.
}
// When the input element is empty
If (o = null ){
For (int I = size-1; I> = 0; I --){
If (elements [I] = null ){
Return I;
}
}
// When not empty
} Else {
For (int I = size-1; I> = 0; I --){
If (o. equals (elements [I]) {
Return I;
}
}
}
Return-1; // not found.-1 is returned.
}
// Custom exception
Private static class EmptyStackException extends RuntimeException {
Public EmptyStackException (){
Super ("Stack is empty ");
}
}
}