php怎么實(shí)現(xiàn)雙向鏈表

PHP
小億
87
2024-06-12 12:57:20

在PHP中實(shí)現(xiàn)雙向鏈表可以通過自定義一個(gè)雙向鏈表類來實(shí)現(xiàn)。下面是一個(gè)簡(jiǎn)單的PHP雙向鏈表的實(shí)現(xiàn)示例:

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

在上面的示例中,我們定義了一個(gè)Node類來表示鏈表節(jié)點(diǎn),包含數(shù)據(jù)$data、指向前一個(gè)節(jié)點(diǎn)的指針$prev和指向后一個(gè)節(jié)點(diǎn)的指針$next。然后我們定義了DoublyLinkedList類來表示雙向鏈表,包含頭節(jié)點(diǎn)$head和尾節(jié)點(diǎn)$tail,并實(shí)現(xiàn)了插入節(jié)點(diǎn)和正向、反向遍歷鏈表的方法。

您可以根據(jù)需要擴(kuò)展該類,添加其他操作方法來實(shí)現(xiàn)更多功能。希望這個(gè)示例能幫助到您。

0