java实现栈的数据结构
栈是一种数据结构,只能从一端进行存储和访问。常规操作有压入栈和弹出栈。
特性:先进先出,LIFO
以下是用ArrayList为内核实现一个栈的数据结构
import java.util.ArrayList; import java.util.List; import java.util.EmptyStackException; public class Statck<E extends Object> { private List<E> pool = new ArrayList<E>(); public Statck() { } public void clear() { pool.clear(); } public boolean isEmpty() { return pool.isEmpty(); } /** * 获取栈顶元素 * */ public E getTopObjcet() { if (isEmpty()) {return null;} return pool.get(pool.size()-1); } /** * 弹出栈操作 * */ public E pop() { if (isEmpty()) {throw new EmptyStackException();} return pool.remove(pool.size() - 1); } /** * 压入栈 * */ public void push(E e) { if (isEmpty()) {throw new EmptyStackException();} pool.add(e); } /** * 获取当前栈大小 * */ public int getStatckSize() { if (isEmpty()) {throw new EmptyStackException();} return pool.size(); } }
以链表方式实现一个栈
public class Statck<E extends Object> { private List<E> pool = new ArrayList<E>(); public Statck() { } public void clear() { pool.clear(); } public boolean isEmpty() { return pool.isEmpty(); } /** * 获取栈顶元素 * */ public E getTopObjcet() { if (isEmpty()) {return null;} return pool.get(0); } /** * 弹出栈操作 * */ public E pop() { if (isEmpty()) {throw new EmptyStackException();} return pool.remove(pool.size() - 1); } /** * 压入栈 * */ public void push(E e) { if (isEmpty()) {throw new EmptyStackException();} pool.add(e); } /** * 获取当前栈大小 * */ public int getStatckSize() { if (isEmpty()) {throw new EmptyStackException();} return pool.size(); } }