链式栈(单向链表实现)
链式栈不需要考虑上溢出(overflow),但在存储时需要增加指针开销。
class ListNode { ListNode next; int val; public ListNode(int x) { val = x; } } public class Stack { private ListNode stack; public Stack() { stack = null; } public void clear() { stack = null; } public void push(int x) { ListNode tmp = new ListNode(x); tmp.next = stack; stack = tmp; } public int pop() throws Exception { if(isEmpty()) throw new Exception("underflow"); else { int val = stack.val; stack = stack.next; return val; } } public int peek() throws Exception{ if(isEmpty()) throw new Exception("underflow"); else return stack.val; } public boolean isEmpty() { return stack == null; } }