以下是一个简单的PHP实现链表的实例,其中包含了链表节点的定义、链表的创建、插入和遍历等功能。
链表节点定义
我们定义一个链表节点的类:
```php
class ListNode {
public $value;
public $next;
public function __construct($value) {
$this->value = $value;
$this->next = null;
}
}
```
创建链表
接下来,我们实现一个创建链表的方法:
```php
function createLinkedList($values) {
$head = null;
$current = null;
foreach ($values as $value) {
$newNode = new ListNode($value);
if ($head === null) {
$head = $newNode;
$current = $head;
} else {
$current->next = $newNode;
$current = $current->next;
}
}
return $head;
}
```
插入节点
现在我们实现一个插入节点的方法:
```php
function insertNode($head, $value, $position) {
$newNode = new ListNode($value);
$current = $head;
if ($position === 0) {
$newNode->next = $head;
return $newNode;
}
$index = 0;
while ($current !== null && $index < $position - 1) {
$current = $current->next;
$index++;
}
if ($current === null) {
return "