S SmartDocs
Chuỗi bài: Angelia java 53 dòng · Cập nhật 2026-09-27

LinkedListChatHistory.java

Angelia/Java/Week_6_7/code/02_adt_interfaces/LinkedListChatHistory.java

/**
 * 實作二:用「鏈結串列」(linked list)保存訊息,數量不受限。
 *
 * 新訊息永遠接在串列最前面(prepend),所以 addMessage 是 O(1),
 * 而且串列本身就是「最新在前」的順序,display 直接走訪即可。
 *
 * 這個類別實作的是 ErasableChatHistory,所以同時也是一個 ChatHistory。
 */
public class LinkedListChatHistory implements ErasableChatHistory {

    /**
     * 靜態巢狀類別(static nested class):一個節點 = 一則訊息 + 指向下一節點的參照。
     * 標成 private:這是實作細節,外界不該知道我們用鏈結串列。
     */
    private static class Node {
        final String msg;
        final Node rest;

        Node(String msg, Node rest) {
            this.msg = msg;
            this.rest = rest;
        }
    }

    private Node head = null;   // null 代表空串列
    private int size = 0;

    @Override
    public void addMessage(String msg) {
        this.head = new Node(msg, this.head);   // 新節點指向舊的 head,再成為新的 head
        this.size = this.size + 1;
    }

    @Override
    public void display() {
        Node current = this.head;
        while (current != null) {
            System.out.println(current.msg);
            current = current.rest;
        }
    }

    @Override
    public int size() {
        return this.size;
    }

    @Override
    public void erase() {
        this.head = null;   // 讓 head 指向 null,所有節點就會被垃圾回收
        this.size = 0;
    }
}

Bài viết liên quan