Links are a basic data structure in computer science. Its elements (called nodes) are connected in turn by pointer. Different from the array, the linked list is dynamic, which means that their size can grow or shrink without the need to adjust the size operation. This tutorial will introduce the basic knowledge of the linked list in PHP.
The structure of the linked list node
Each node in the linked list consists of two parts:
Data: The value stored in the node.
Implement a simple linked list
<code class="language-php">class Node { public $data; public $next; public function __construct($data) { $this->data = $data; $this->next = null; } }</code>
In order to manage the node, we create a LinkedList class that provides a method for the maintenance list and provides the method of operating it.
Basic operation
<.> 1. Add the node to the end
We add the node to the end of the list by reaching the iterative node until the last node reaches the last node.<.> 2. Show the list
We can traverse the list to print all elements.
<code class="language-php">class LinkedList { private $head; public function __construct() { $this->head = null; } public function append($data) { $newNode = new Node($data); if ($this->head === null) { $this->head = $newNode; } else { $current = $this->head; while ($current->next !== null) { $current = $current->next; } $current->next = $newNode; } } }</code>
<.> 3. Delete nodes
Delete nodes include finding nodes and updating the pointer of the previous node.
<code class="language-php">public function display() { $current = $this->head; while ($current !== null) { echo $current->data . " -> "; $current = $current->next; } echo "NULL\n"; }</code>
Example usage
The following is a method of implementing the linked list:
<code class="language-php">public function delete($data) { if ($this->head === null) { return; } if ($this->head->data === $data) { $this->head = $this->head->next; return; } $current = $this->head; while ($current->next !== null && $current->next->data !== $data) { $current = $current->next; } if ($current->next !== null) { $current->next = $current->next->next; } }</code>
Conclusion
<code class="language-php">$linkedList = new LinkedList(); $linkedList->append(10); $linkedList->append(20); $linkedList->append(30); echo "初始列表:\n"; $linkedList->display(); $linkedList->delete(20); echo "删除 20 后:\n"; $linkedList->display();</code>
The above is the detailed content of Introduction to Linked Lists in PHP: A Beginners Guide. For more information, please follow other related articles on the PHP Chinese website!