📚 数据结构基础:(2)栈的基本实现
需要用到自定义数组类:https://www.cnblogs.com/cenjw/p/custom-array-class.html
先定义一个栈的接口
public interface Stack<E> {
int getSize();
boolean isEmpty();
void push(E e);
E pop();
E peek();
}
接口的实现类
class ArrayStack<E> implements Stack<E> {
Array<E> array;
// 构造函数
public ArrayStack(int capacity) {
array = new Array<>(capacity);
}
public ArrayStack() {
array = new Array<>();
}
@Override
public int getSize() {
return array.getSize();
}
@Override
public boolean isEmpty() {
return array.isEmpty();
}
public int getCapacity() {
return array.getCapacity();
}
@Override
public void push(E e) {
array.addLast(e);
}
@Override
public E pop() {
return array.removeLast();
}
@Override
public E peek() {
return array.getLast();
}
@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 != getSize()-1) {
res.append(",");
}
}
res.append("] top");
return res.toString();
}
}
本文来自博客园,作者:micromatrix,转载请注明原文链接:https://www.cnblogs.com/cenjw/p/basic-implementation-of-stack.html
posted on 2022-03-04 21:39 micromatrix 阅读(23) 评论(0) 编辑 收藏 举报