單向鏈結串列由節點組成,每個節點包含 資料 與 指向下一個節點的指標。PHP 雖無原生指標,但物件預設為參考傳遞,可直接模擬指標行為。
class Node {
private $id;
public $name;
public $next = null;
public function __construct($id = '', $name = '') {
$this->id = $id;
$this->name = $name;
}
// 取得私有 id(示範封裝)
public function getId() { return $this->id; }
}
採用虛擬頭節點簡化邊界條件:$head 本身不存資料,$head->next 指向第一個真實節點。
static public function show($head) {
$cur = $head;
while ($cur->next) {
echo $cur->next->id . '###' . $cur->next->name . "
\n";
$cur = $cur->next;
}
echo "
\n";
}
static public function push($head, $node) {
$cur = $head;
while ($cur->next !== null) {
$cur = $cur->next;
}
$cur->next = $node;
return $head;
}
static public function insert($head, $node) {
$cur = $head;
while ($cur->next !== null) {
if ($cur->next->id > $node->id) break;
$cur = $cur->next;
}
$node->next = $cur->next;
$cur->next = $node;
return $head;
}
static public function edit($head, $node) {
$cur = $head;
while ($cur->next !== null) {
if ($cur->next->id == $node->id) break;
$cur = $cur->next;
}
if ($cur->next !== null) {
$cur->next->name = $node->name;
}
return $head;
}
static public function pop($head, $node) {
$cur = $head;
while ($cur->next !== null) {
if ($cur->next === $node) break;
$cur = $cur->next;
}
if ($cur->next !== null) {
$cur->next = $node->next;
}
return $head;
}
$head = new Node(); // 虛擬頭節點 $n1 = new Node(1, '唐三藏'); Node::push($head, $n1); $n1->name = '唐僧'; // 物件參考傳遞,直接修改生效 Node::show($head); $n2 = new Node(2, '孫悟空'); Node::insert($head, $n2); $n3 = new Node(5, '白龍馬'); Node::push($head, $n3); $n4 = new Node(3, '豬八戒'); Node::insert($head, $n4); $n5 = new Node(4, '沙和尚'); Node::insert($head, $n5); $n4->name = '豬悟能'; // 同樣直接修改 Node::pop($head, $n1); // 刪除第一個節點 Node::show($head);
1###唐僧 2###孫悟空 3###豬八戒 4###沙和尚 5###白龍馬 --- 2###孫悟空 3###豬悟能 4###沙和尚 5###白龍馬 ---
$n1->name = '新名' 直接影響鏈結串列內節點,無需額外 edit 呼叫$cur->next = $node->next)後無引用的節點會被回收findById、reverse、toArray 等工具方法