java data structures - stack underlying implementation: array implemented push, pop, empty stack is determined

com.stack Package; 

/ **
* @auther strong Fu
* @date 2020/2/13 - 12:45
* /
public class MyStack {
// We use the underlying stack array to store data
int [] Elements;
public MyStack ( ) {
elements = new new int [0];
}
// element pressed
public void Push (int element) {
// create a new array
int [] = newArr new new int [elements.length +. 1];
// the original elements of the array to the new array
for (int I = 0; I <elements.length; I ++) {
newArr [I] = elements [I];
}
// the element to be added into the new array
newArr [elements.length] = element;
// replace it with a new array array
elements = newArr;
}
// remove the top element
int POP public () {
// do not stack element
IF (elements.length == 0) {
the throw a RuntimeException new new ( "empty Stack IS");
}
// remove the last element of the array
int element = elements [elements.length --1];
// Create a new array
int [] = newArr new new int [elements.length-1];
// process the other elements of the original array are placed in the last element of the new array
for (int i = 0; I <elements.length -. 1; I ++) {
newArr [I] = elements [I];
}
// alternative array
elements = newArr;
// return the top element
return element;
}
// Check the top element
public int Pick () {
// no element in the stack
if (elements.length == 0) {
throw new RuntimeException("stack is empty");
}
return elements[elements.length-1];
}
//判断栈是否为空
public boolean isEmpty(){
return elements.length==0;
}

}

Guess you like

Origin www.cnblogs.com/fuqiang-java/p/12303305.html