鏈結串列在記憶體中非連續儲存,透過指標串連節點,解決陣列插入/刪除效能瓶頸。本文以「水滸傳好漢」為例,示範 PHP 實作單向鏈結串列的節點定義、建立、遍歷。
<?php
/** 英雄節點類別 */
class Hero {
public $no;
public $name;
public $nickname;
public $next = null;
public function __construct($no = '', $name = '', $nickname = '')
{
$this->no = $no;
$this->name = $name;
$this->nickname = $nickname;
}
}
/** 鏈結串列操作示範 */
class LinkListDemo {
public static function main()
{
// 建立頭節點(不存資料)
$head = new Hero();
// 建立節點並串連
$hero1 = new Hero(1, "宋江", "及時雨");
$head->next = $hero1;
$hero2 = new Hero(2, "盧俊義", "玉麒麟");
$hero1->next = $hero2;
// 遍歷列印
self::showHeros($head);
}
public static function showHeros($head)
{
$cur = $head;
while ($cur->next != null) {
echo "姓名:" . $cur->next->name . "<br/>";
$cur = $cur->next;
}
}
}
LinkListDemo::main();
$next 屬性儲存的是下一個 Hero 物件的參考(指標)$cur = $cur->next 移動指標文中也提供對應 Java 版本,邏輯完全一致,僅語法差異,適合跨語言學習參考。
單向鏈結串列是理解雙向鏈結、環狀鏈結、跳表等進階結構的基礎,掌握其指標操作觀念至關重要。