public class StackLinked {
    StackNode top;
    int size;

    int size() {
        return size;
    }

    boolean isEmpty() {
        return top == null;
    }

    void push(int data) {
        if (top == null) {
            top = new StackNode(data, null);
            size++;
            return;
        }
        top = new StackNode(data, top);
        size++;
    }

    int pop() {
        if (top == null) {
            throw new EmptyStackException();
        }
        int data = top.data;
        top = top.next;
        size--;
        return data;
    }

    int peek() {
        if (top == null) {
            throw new EmptyStackException();
        }
        return top.data;
    }


    public static void main(String[] args) {
        StackLinked s=new StackLinked();
        s.push(1);
        s.push(2);
        s.push(3);
        System.out.println("size->"+s.size());
        System.out.println("s.pop->"+s.pop());
        System.out.println("s.pop->"+s.pop());
        s.push(4);
        System.out.println("s.pop->"+s.pop());
        System.out.println("s.isEmpty->"+s.isEmpty());
        System.out.println("s.peek->"+s.peek());
        System.out.println("s.pop->"+s.pop());
        System.out.println("s.isEmpty->"+s.isEmpty());

    }
}

class StackNode {
    int data;
    StackNode next;

    StackNode(int data, StackNode stackNode) {
        this.data = data;
        this.next = stackNode;
    }
}
最后修改:2021 年 09 月 16 日 07 : 38 PM