Java語言使用泛型和LinkedList模擬棧操作

方法說明

  • pop():獲取棧頂元素
  • push():將元素壓入棧
  • end():判斷棧空

Java代碼

public class LinkedList<T> {
    private static class Node<U> {
        U item;
        Node<U> next;

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

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

        boolean end() {
            return item == null && next == null;
        }
    }

    private Node<T> top = new Node<T>();

    public void push(T item) {
        top = new Node<T>(item, top);
    }

    public T pop() {
        T result = top.item;
        if (!top.end()) {
            top = top.next;
        }
        return result;
    }

    public static void main(String[] args) {
        LinkedList<String> lss = new LinkedList<>();
        for (String s : "Follow Your Heart!".split(" ")) {
            lss.push(s);
        }

        String s;
        while ((s = lss.pop()) != null)
            System.out.println(s);
    }
}

樣例輸出

Heart!
Your
Follow

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章