自己实现数据结构系列三---Stack
一.代码部分
1.定义接口
public interface Stack<E> { int getSize(); boolean isEmpty(); void push(E e); E pop(); E peek(); }
2.基于数组实现:
public class ArrayStack<E> implements Stack<E> { ArrayList<E> arrayList; public ArrayStack(int capacity){ arrayList = new ArrayList(capacity); } public ArrayStack(){ arrayList = new ArrayList<E>(); } @Override public int getSize() { return arrayList.getSize(); } @Override public boolean isEmpty() { return arrayList.isEmpty(); } @Override public void push(E e) { arrayList.addLast(e); } @Override public E pop() { return arrayList.removeLast(); } @Override public E peek() { return arrayList.get(getSize()-1); } public int getCapacity(){ return arrayList.getCapacity(); } @Override public String toString() { StringBuilder res = new StringBuilder(); res.append("Stack:"); res.append("["); for (int i = 0; i < arrayList.getSize(); i++) { res.append(arrayList.get(i)); if(i != arrayList.getSize()-1){ res.append(","); } } res.append("] top"); return res.toString(); } }
3.基于链表实现:
public class LinkedListStack<E> implements Stack<E> { private LinkedListPlus<E> list; public LinkedListStack(){ list = new LinkedListPlus<>(); } @Override public int getSize() { return list.getSize(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public void push(E e) { list.addFirst(e); } @Override public E pop() { return list.removeFirst(); } @Override public E peek() { return list.getFirst(); }
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append("stack:top");
res.append(list);
return res.toString();
} }