在PHP中實現雙向鏈表可以通過自定義一個雙向鏈表類來實現。下面是一個簡單的PHP雙向鏈表的實現示例:
class Node {
public $data;
public $prev;
public $next;
public function __construct($data) {
$this->data = $data;
$this->prev = null;
$this->next = null;
}
}
class DoublyLinkedList {
private $head;
private $tail;
public function __construct() {
$this->head = null;
$this->tail = null;
}
public function insertAtEnd($data) {
$newNode = new Node($data);
if ($this->head === null) {
$this->head = $newNode;
$this->tail = $newNode;
} else {
$newNode->prev = $this->tail;
$this->tail->next = $newNode;
$this->tail = $newNode;
}
}
public function displayForward() {
$current = $this->head;
while ($current !== null) {
echo $current->data . " ";
$current = $current->next;
}
echo "\n";
}
public function displayBackward() {
$current = $this->tail;
while ($current !== null) {
echo $current->data . " ";
$current = $current->prev;
}
echo "\n";
}
}
// 使用示例
$linked_list = new DoublyLinkedList();
$linked_list->insertAtEnd(1);
$linked_list->insertAtEnd(2);
$linked_list->insertAtEnd(3);
$linked_list->displayForward(); // 輸出: 1 2 3
$linked_list->displayBackward(); // 輸出: 3 2 1
在上面的示例中,我們定義了一個Node
類來表示鏈表節點,包含數據$data
、指向前一個節點的指針$prev
和指向后一個節點的指針$next
。然后我們定義了DoublyLinkedList
類來表示雙向鏈表,包含頭節點$head
和尾節點$tail
,并實現了插入節點和正向、反向遍歷鏈表的方法。
您可以根據需要擴展該類,添加其他操作方法來實現更多功能。希望這個示例能幫助到您。