链表是由一组节点组成的集合。每个节点都使用一个对象的引用指向它的后继。指向另一个节点的引用叫做链。
链表分为单链表、双链表、循环链表。
一、单链表
插入:链表中插入一个节点的效率很高。向链表中插入一个节点,需要修改它前面的节点(前驱),使其指向新加入的节点,而新加入的节点则指向原来前驱指向的节点(见下图)。
由上图可知,B、C之间插入D,三者之间的关系为
current为插入节点的前驱节点
new->next = current->next // 新节点D指向B的后继节点C
current->next = new // B节点指向新节点D
删除:从链表中删除一个元素,将待删除元素的前驱节点指向待删除元素的后继节点,同时将待删除元素指向 null,元素就删除成功了(见下图)。
由上图可知,A、C之间删除B,三者之间的关系为
current为要删除节点的前驱节点
current->next = current->next->next // A节点指向C节点
具体代码如下:
<?php
// 节点类
class Node {
public $data; // 节点数据
public $next; // 下一节点
public function __construct($data) {
$this->data = $data;
$this->next = NULL;
}
}
// 单链表类
class SingleLinkedList {
private $header; // 头节点
function __construct($data) {
$this->header = new Node($data);
}
// 查找节点
public function find($item) {
$current = $this->header;
while ($current->data != $item) {
$current = $current->next;
}
return $current;
}
// (在节点后)插入新节点
public function insert($item, $new) {
$newNode = new Node($new);
$current = $this->find($item);
$newNode->next = $current->next;
$current->next = $newNode;
return true;
}
// 更新节点
public function update($old, $new) {
$current = $this->header;
if ($current->next == null) {
echo "链表为空!";
return;
}
while ($current->next != null) {
if ($current->data == $old) {
break;
}
$current = $current->next;
}
return $current->data = $new;
}
// 查找待删除节点的前一个节点
public function findPrevious($item) {
$current = $this->header;
while ($current->next != null && $current->next->data != $item) {
$current = $current->next;
}
return $current;
}
// 从链表中删除一个节点
public function delete($item) {
$previous = $this->findPrevious($item);
if ($previous->next != null) {
$previous->next = $previous->next->next;
}
}
// findPrevious和delete的整合
public function remove($item) {
$current = $this->header;
while ($current->next != null && $current->next->data != $item) {
$current = $current->next;
}
if ($current->next != null) {
$current->next = $current->next->next;
}
}
// 清空链表
public function clear() {
$this->header = null;
}
// 显示链表中的元素
public function display() {
$current = $this->header;
if ($current->next == null) {
echo "链表为空!";
return;
}
while ($current->next != null) {
echo $current->next->data . "  ";
$current = $current->next;
}
}
}
$linkedList = new SingleLinkedList('header');
$linkedList->insert('header', 'China');
$linkedList->insert('China', 'USA');
$linkedList->insert('USA','England');
$linkedList->insert('England','Australia');
echo '链表为:';
$linkedList->display();
echo "</br>";
echo '-----删除节点USA-----';
echo "</br>";
$linkedList->delete('USA');
echo '链表为:';
$linkedList->display();
echo "</br>";
echo '-----更新节点England为Japan-----';
echo "</br>";
$linkedList->update('England', 'Japan');
echo '链表为:';
$linkedList->display();
//echo "</br>";
//echo "-----清空链表-----";
//echo "</br>";
//$linkedList->clear();
//$linkedList->display();
// 输出:
链表为:China USA England Australia
-----删除节点USA-----
链表为:China England Australia
-----更新节点England为Japan-----
链表为:China Japan Australia