以下是使用PHP实现的一个简单有序链表的示例。我们将创建一个有序链表类,并展示如何添加元素、排序、遍历等操作。
类定义
```php

class SortedLinkedList {
private $head;
public function __construct() {
$this->head = null;
}
// 添加元素到有序链表
public function insert($data) {
$newNode = new ListNode($data);
if ($this->head === null || $data < $this->head->data) {
$newNode->next = $this->head;
$this->head = $newNode;
} else {
$current = $this->head;
while ($current->next !== null && $current->next->data < $data) {
$current = $current->next;
}
$newNode->next = $current->next;
$current->next = $newNode;
}
}
// 遍历链表
public function traverse() {
$current = $this->head;
while ($current !== null) {
echo $current->data . "









