雙向鏈結清單(Doubly Linked List)是線性資料結構,每個節點包含資料、前驅指標與後繼指標,支援雙向遍歷、首尾快速插入刪除,時間複雜度 O(1)。

| 方法 | 說明 |
|---|---|
push($value) | 尾部新增元素 |
pop() | 移除並回傳尾部元素 |
unshift($value) | 頭部新增元素 |
shift() | 移除並回傳頭部元素 |
add($index, $newval) | 指定索引插入元素 |
top() | 回傳頭部元素(不移除) |
bottom() | 回傳尾部元素(不移除) |
count() | 元素總數 |
isEmpty() | 是否為空 |
offsetGet/Set/Unset/Exists | ArrayAccess 介面支援 |
setIteratorMode() | 設定迭代模式(FIFO/LIFO、KEEP/DELETE) |
serialize()/unserialize() | 序列化與反序列化 |
$list = new SplDoublyLinkedList();
$list->push('a');
$list->push('b');
$list->push('c');
$list->unshift('top'); // 頭部插入
$list->shift(); // 移除頭部
print_r(array(
'pop' => $list->pop(),
'count' => $list->count(),
'isEmpty' => $list->isEmpty(),
'bottom' => $list->bottom(),
'top' => $list->top()
));
// 設定 FIFO 迭代(隊列模式)
$list->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO);
print_r($list->getIteratorMode());
// 遍歷輸出
for ($list->rewind(); $list->valid(); $list->next()) {
echo $list->current() . PHP_EOL;
}
// 序列化測試
$a = $list->serialize();
print_r($a);
// 索引操作
$list->offsetSet(0, 'new one');
$list->offsetUnset(0);
print_r(array(
'offsetExists' => $list->offsetExists(4),
'offsetGet' => $list->offsetGet(0),
));
print_r($list);
IT_MODE_LIFO(堆疊模式):後進先出IT_MODE_FIFO(隊列模式):先進先出IT_MODE_KEEP:迭代不移除元素IT_MODE_DELETE:迭代時移除元素