Stack is a data structure of "last-in-first-out (LIFO)". recently pushed data items are always at the top of the stack.
First, we define a Stack Interface and define it as a generic Interface.
/*** Stack interface ** @ author Chris Wang ** @ param <E> */public interface Stack <E> {/*** determines whether the Stack is empty * @ return * /public boolean isEmpty (); /*** return the number of elements in the stack * @ return */public int size (); /*** import stack ** @ param target **/public void push (E target);/*** output stack ** @ return E */public E pop (); /*** return the top element of the stack, and the stack does not exist * @ return */public E top ();}
Then implement ArrayStack using arrays in Java. The following code is used:
Code
/**
* Array-based stack implementation
*
* @ Author Chris Wang
* @ Param <E>
*/
Public class ArrayStack <E> implements Stack <E> {
/**
* Indicates the elements to be stored in the stack.
*/
Private E [] data;
/**
* Indicates the current stack capacity.
*/
Private int size = 0;
Public ArrayStack (){
Data = (E []) new Object [10];
// The element in the stack is empty at the beginning.
Size = 0;
}
Public int size (){
Return size;
}
Public boolean isEmpty (){
Return size <1;
}
/**
* The top element of the stack is returned, but the stack does not exist.
*/
Public E top (){
If (isEmpty ()){
Throw new RuntimeException ("the linked list is empty !! ");
}
Return data [size-1];
}
/**
* Output Stack
*/
Public E pop (){
If (isEmpty ()){
Throw new RuntimeException ("the linked list is empty !! ");
}
// First save the top element of the stack
E element = data [size-1];
// Then clear the top element of the stack,
Data [size] = null;
// Reduce one element in the stack
Size --;
Return element;
}
/**
* When the stack is added, first determine whether the stack is full. If the stack is full, it is expanded.
*/
Public void push (E target ){
If (target = null)
Throw new RuntimeException ("the inserted element cannot be NULL ");
If (isFull ()){
Enlarge ();
}
Size ++;
// Add an element to the top of the stack
Data [size-1] = target;
}
/**
* Extended array length note: Generally, after the stack is determined to be full, it is expanded to twice the length of the original array.
*/
Public void enlarge (){
E [] newData = (E []) new Object [data. length * 2];
For (int I = 0; I <size; I ++ ){
NewData [I] = data [I];
}
Data = newData;
}
/**
* If the array length is equal to the number of elements in the stack, the stack is full.
*
* @ Return
*/
Public boolean isFull (){
Return data. length = size;
}
}