写在前面
本系列代码Gitee地址为点击这里
接口 Stack.java
public interface Stack<E> {
// 入栈
void push(E e);
// 出栈
E pop();
// 查看栈顶元素
E peek();
// 返回栈的大小
int getSize();
// 判断栈是否为空
boolean isEmpty();
}
实现 ArrayStack.java(数组栈)
public class ArrayStack<E> implements Stack<E> {
private Array<E> array;
public ArrayStack(int capacity) {
array = new Array<E>(capacity);
}
public ArrayStack() {
array = new Array<E>();
}
@Override
public E peek() {
return array.getLast();
}
@Override
public E pop() {
return array.removeLast();
}
@Override
public void push(E e) {
array.addLast(e);
}
@Override
public boolean isEmpty() {
return array.isEmpty();
}
@Override
public int getSize() {
return array.getSize();
}
public int getCapacity() {
return array.getCapacity();
}
@Override
public String toString() {
return String.format("Stack: size = %d, capacity = %d\n",
array.getSize(), array.getCapacity()) +
array + " top";
}
}
实现LinkedListStack.java(链表栈)
public class LinkedListStack<E> implements Stack<E> {
private LinkedList<E> linkedList;
public LinkedListStack() {
linkedList = new LinkedList<E>();
}
@Override
public void push(E e) {
linkedList.addFirst(e);
}
@Override
public E pop() {
return linkedList.removeFirst();
}
@Override
public E peek() {
return linkedList.getFirst();
}
@Override
public int getSize() {
return linkedList.getSize();
}
@Override
public boolean isEmpty() {
return linkedList.isEmpty();
}
@Override
public String toString() {
return "Stack: top " + linkedList;
}
}