数据机构-stack-链式结构

65 阅读1分钟
static class Stack {
    Node top;
    Node base;
    int size;

    public Stack() {
        this.top = new Node();
        this.base = new Node();
        top.next = base;
        size = 0;
    }

    public void push(int value) {
        Node node = new Node(value);
        node.next = top;
        top = node;
        size++;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("you stack is empty");
        }
        Node node = top;
        int value = node.value;
        top = node.next;
        size--;
        return value;
    }


    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("you stack is empty");
        }
        return top.value;
    }

    public boolean isEmpty() {
        return top.next == base;
    }

}