一.代码部分
1.定义接口
public interface Stack{ int getSize(); boolean isEmpty(); void push(E e); E pop(); E peek();}
2.基于数组实现:
public class ArrayStackimplements Stack { ArrayList arrayList; public ArrayStack(int capacity){ arrayList = new ArrayList(capacity); } public ArrayStack(){ arrayList = new ArrayList (); } @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 LinkedListStackimplements Stack { private LinkedListPlus 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(); }}