PHP

php怎么实现双向链表

小亿
87
2024-06-12 12:57:20
栏目: 编程语言

在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,并实现了插入节点和正向、反向遍历链表的方法。

您可以根据需要扩展该类,添加其他操作方法来实现更多功能。希望这个示例能帮助到您。

0
看了该问题的人还看了