php实现一个双向链表
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 insertAtFront($data) {
$newNode = new Node($data);
if ($this->head === null) {
$this->head = $newNode;
$this->tail = $newNode;
} else {
$newNode->next = $this->head;
$this->head->prev = $newNode;
$this->head = $newNode;
}
}
public function deleteAtEnd() {
if ($this->tail !== null) {
if ($this->head === $this->tail) {
$this->head = null;
$this->tail = null;
} else {
$prevNode = $this->tail->prev;
$prevNode->next = null;
$this->tail = $prevNode;
}
}
}
public function deleteAtFront() {
if ($this->head !== null) {
if ($this->head === $this->tail) {
$this->head = null;
$this->tail = null;
} else {
$nextNode = $this->head->next;
$nextNode->prev = null;
$this->head = $nextNode;
}
}
}
public function display() {
$current = $this->head;
while ($current !== null) {
echo $current->data . " ";
$current = $current->next;
}
echo "\n";
}
}
$linkedList = new DoublyLinkedList();
$linkedList->insertAtEnd(1);
$linkedList->insertAtEnd(2);
$linkedList->insertAtEnd(3);
$linkedList->insertAtEnd(4);
$linkedList->insertAtEnd(5);
$linkedList->display(); // 1 2 3 4 5
$linkedList->deleteAtEnd();
$linkedList->deleteAtFront();
$linkedList->display(); // 2 3 4
原文地址: http://www.cveoy.top/t/topic/Jnp 著作权归作者所有。请勿转载和采集!