链表由一个一个的做为节点的对象构成的,每个节点都有指向下一个节点的指针,最后一个节点的指针域指向空。每一个节点能够存储任何数据类型。git
对单链表咱们常见的操做有以下:github
首先咱们根据定义实现一个ListNode类。web
class ListNode {
private $data;
private $next;
public function __construct(string $data) {
$this->data = $data;
}
public function __get($var) {
return $this->$var;
}
public function __set($var, $val) {
return $this->$var = $val;
}
}
复制代码
再来看链表类,首先须要2个私有属性,分别是头节点和长度。算法
class LinkedList {
private $head;
private $length;
}
复制代码
下面咱们长话短说,直接看如何实现第一个即经常使用的插入,这是是一个平均时间复杂度为O(n)的操做。数据结构
/** * 插入一个节点 * @param string|null $data * @return bool * complexity O(n) */
public function insert(string $data = null) {
$newNode = new ListNode($data);
if ($this->head === null) {
$this->head = &$newNode;
} else {
$currentNode = $this->head;
while ($currentNode->next !== null) {
$currentNode = $currentNode->next;
}
$currentNode->next = $newNode;
}
$this->length++;
return true;
}
复制代码
再来看搜索,一样是一个平均时间复杂度为O(n)的操做。数据结构和算法
/** * 搜索一个节点 * @param string $data * @return bool|ListNode * complexity O(n) */
public function search(string $data) {
if ($this->length > 0) {
$currentNode = $this->head;
while ($currentNode !== null) {
if ($currentNode->data === $data) {
return $currentNode;
}
$currentNode = $currentNode->next;
}
}
return false;
}
复制代码
反转单链表优化
public function reverse() {
if ($this->head !== null) {
if ($this->head->next !== null) {
$reveredList = null;
$next = null;
$currentNode = $this->head;
while ($currentNode !== null) {
$next = $currentNode->next;
$currentNode->next = $reveredList;
$reveredList = $currentNode;
$currentNode = $next;
}
$this->head = $reveredList;
}
}
}
复制代码
单链表其余操做的详细实现能够参考 这里。this
单链表是链表这种链式存取数据结构中基础的部分,一样属于链表结构的还有双链表,环形链表和多链表。spa
PHP基础数据结构专题系列目录地址:github.com/... 主要使用PHP语法总结基础的数据结构和算法。还有咱们平常PHP开发中容易忽略的基础知识和现代PHP开发中关于规范、部署、优化的一些实战性建议,同时还有对Javascript语言特色的深刻研究。指针