Java泛型 自定义栈Stack

public class LinkedStack<T> {
    //末端哨兵
    private static class Node<U> {
        Node<U> next;
        U item;

        Node() {
            next = null;
            item = null;
        }

        public Node(Node<U> next, U item) {
            this.next = next;
            this.item = item;
        }

        public boolean end() {
            return next == null && item == null;
        }
    }
    private Node<T> top = new Node<>();
    public void push(T item){
        top = new Node<>(top, item);
    }
    public T pop(){
        T item = top.item;
        if(!top.end())
            top = top.next;
        return item;
    }

    public static void main(String[] args) {
        LinkedStack<String> stack = new LinkedStack<>();
        for (String s: "sss aaa qqq".split(" ")) {
            stack.push(s);
        }
        String s;
        while ((s = stack.pop()) != null){
            System.out.println(s);
        }
    }
}

采取了内部类定义一个末端哨兵来判断栈是否为空。

猜你喜欢

转载自blog.csdn.net/JOKER_SAMA/article/details/81558260