链式栈(单向链表实现)

链式栈不需要考虑上溢出(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;
    }
}

 

posted @ 2015-10-05 16:10  lasclocker  阅读(235)  评论(0编辑  收藏  举报