In this paper, we introduce stack, and use array as the underlying structure to write stack code.
What is a stack: A stack represents an advanced data structure, and the stack only allows access to one data item, that is, the last inserted data item, that is, the data item on the top of the stack. The data item behind the top of the stack must be removed before it can be accessed.
First, create a Stack interface to support generics, which defines the following classes:
getSize: View the number of elements on the stack
isEmpty: Check if the stack is empty
pop: Take out the elements on the top of the stack
peek: Look at the top element of the stack
push: to add an element to the stack
package Stack;
public interface Stack <E>{
int getSize();
boolean isEmpty();
E pop();
E peek();
void push(E e);
}
Define the ArrayStack class to support generic programming for interface Stack. The following code is the construction method of the ArrayStack class.
The first constructor, passing in the specified parameter, opens an array of capacity capacity in memory
The second parameter-free construction method defaults to an initial capacity of 10.
The Array class reference: https://blog.csdn.net/qq_44313091/article/details/97539644
public class ArrayStack<E> implements Stack<E>{
Array<E> array;
public ArrayStack(int capacity) {
array =new Array<>(capacity);
}
public ArrayStack() {
array =new Array<>(10);
}}
The following method implements all classes in the interface
@Override
public int getSize() {
return array.getsize();
}
@Override
public boolean isEmpty() {
return array.isEmpty();
}
@Override
public void push(E e) {
array.addLast(e);
}
@Override
public E pop () {
return array.removeLast();
}
@Override
public E peek () {
return array.getLast();
}
Finally, the toString method is rewritten
@Override
public String toString () {
StringBuilder res =new StringBuilder();
res.append("Stack:");
res.append("[");
for(int i=0;i<array.getsize();i++) {
res.append(array.get(i));
if(i!=array.getsize()-1) {
res.append(",");
}
}
res.append("] top");
return res.toString();
}