雙向循環鏈表 是經典資料結構,每個節點同時擁有 prev 與 next 指標,首尾相接形成環狀。本實作針對「多條鏈表共存時長度統計互不干擾」的問題,引入 Map<String, Integer> sizeMap 配合唯一 linkedId 機制,避免單一 static int size 導致多鏈表長度錯亂。
public class BothwayLoopLinked {
// 靜態 Map:key=linkedId, value=該鏈表當前長度
private static final Map<String, Integer> sizeMap = new HashMap<>();
private String linkedId; // 所屬鏈表唯一 ID
private Object data; // 節點資料
private BothwayLoopLinked prev = this; // 初始指向自己
private BothwayLoopLinked next = this; // 初始指向自己
// ... 建構子與操作方法
}
以 insertAfter 為例:
oldBefore = this、原後節點 oldAfter = this.next。oldBefore.next = newLinked、newLinked.prev = oldBefore、oldAfter.prev = newLinked、newLinked.next = oldAfter。changeSize(+1) 更新對應 linkedId 的長度計數。newLinked.linkedId = this.linkedId 綁定新節點至同一鏈表。insertBefore 邏輯鏡像對稱,僅交換前後節點角色。
public BothwayLoopLinked remove(BothwayLoopLinked linked) {
linked.prev.next = linked.next;
linked.next.prev = linked.prev;
changeSize(-1);
linked.prev = linked.next = linked; // 斷開自身引用,便於 GC
linked.linkedId = null;
return linked;
}
移除後將節點指標指回自己,切斷與原鏈表關聯,避免記憶體洩漏。
private void changeSize(int delta) {
if (linkedId == null) return;
sizeMap.merge(linkedId, delta, Integer::sum);
if (sizeMap.get(linkedId) == 0) sizeMap.remove(linkedId);
}
使用 Map.merge 原子更新,長度歸零時自動清理 Map 條目。
// 建立第一個節點並指定鏈表 ID
BothwayLoopLinked head = new BothwayLoopLinked();
head.linkedId = UUID.randomUUID().toString();
// 依序插入
head.insertAfter(new BothwayLoopLinked()); // 第 2 節點
head.next.insertAfter(new BothwayLoopLinked()); // 第 3 節點
// 取得長度
int len = sizeMap.get(head.linkedId); // 3
// 移除中間節點
head.next.remove(); // 長度變 2
linkedId + sizeMap 完美解決多實例長度統計衝突。linkedId。insertAfter/Before、remove 語義清晰,符合慣用習慣。Object,可攜帶任意業務物件。完整原始碼請參考文章開頭的程式區塊,可直接複製到專案中使用或依需求擴充(如迭代器、序列化等)。