棧是一種數據結構,只能從一端進行存儲和訪問。常規操作有壓入棧和彈出棧。
特性:先進先出,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(); } }