系列: Angelia
java
53 行
· 更新于 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;
}
}
相关文章
Angelia
haskell
EN
更新于 2026-02-03
Adding.hs
Adding.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Adding.hs).
阅读文章 →
Angelia
haskell
EN
更新于 2026-02-03
Area.hs
Area.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Area.hs).
阅读文章 →
Angelia
haskell
EN
更新于 2026-02-03
Chess.hs
Chess.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Chess.hs).
阅读文章 →
Angelia
haskell
EN
更新于 2026-02-03
ChessGraphics.hs
ChessGraphics.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/ChessGraphics.hs).
阅读文章 →
Angelia
haskell
EN
更新于 2026-02-03
Examples.hs
Examples.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Examples.hs).
阅读文章 →
Angelia
haskell
EN
更新于 2026-02-03
Fibonacci.hs
Fibonacci.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Fibonacci.hs).
阅读文章 →