说明:PHP实现单链表
1、节点类
class node{
public $key; //索引
public $value; //值
public $lastNode; //上个节点
//初始化
public function __construct($key, $value, $lastNode = NULL)
{
$this->key = $key;
$this->value = $value;
$this->lastNode = $lastNode;
}
}
2、链表类
class nodeTable{
public $node; //当前节点
public $length; //当前长度
public function __construct()
{
$this->length = 0;
$this->node = null;
echo "初始化单链表";
}
//增加一个节点
public function createNode($value)
{
$key = $this->length++;
//判断当前节点是否为空
if (empty($this->node)) {
$this->node = (new node($key, $value));
echo "头节点";
} else {
$currentNode = (new node($key, $value));
//把当前节点放在新创建节点的lastNode
$currentNode->lastNode = $this->node;
//把新增加节点加入结尾
$this->node = $currentNode;
echo "身体节点";
}
}
//返回当前节点
public function currentNode()
{
//判断长度
if ( $this->length == 0 ) {
return "当前节点并未创建";
}
return $this->node;
}
//返回指定节点
public function infoNode($length)
{
$len = $this->length;
$node = $this->node;
//判断指定节点长度是否存在
if ($length > $len) {
return "指定节点不存在";
} else {
$count = $len - $length;
if ($count == 0) {
return $node;
}
for ($i = 0; $i < $count; $i++) {
$node = $node->lastNode;
}
}
return $node;
}
//删除指定节点
public function deleteNode($length)
{
$len = $this->length;
$node = $this->node;
//判断指定节点长度是否存在
if ($length > $len) {
return "该节点不存在";
}
//节点存在,若长度刚好是最后一个
if ($length == $len) {
//将当前节点放在tem, 并且将当前节点置为0,
//最后将上一个节点置为当前节点
$tem = $this->node;
$this->node = null;
$this->node = $tem->lastNode;
$this->length--;
} else {
//找指定节点
$count = $len - $length;
for ($i = 0; $i < $count; $i++) {
$nextnode = $node;
$node = $node->lastNode;
}
//裁掉找到的节点,并将链表长度减一
$nextnode->lastNode = $node->lastNode;
$this->length--;
}
//重新归并索引
$len = $this->length;
//重新拿取删除过的节点
$node = $this->node;
while (!empty($node)) {
$node->key = --$len;
$node = $node->lastNode;
}
//返回当前节点
return $this->node;
}
}
3、测试实例
$linked = new nodeTable();
$linked->createNode(5435);
$linked->createNode("haha");
$linked->createNode("faffa");
$currentNode = $linked->currentNode();
echo "<pre>";
print_r($currentNode);
echo "<hr>";
echo "<pre>";
print_r($linked->infoNode(3));
echo "<hr>";
echo "<pre>";
print_r($linked->deleteNode(2));
print_r($linked->deleteNode(2));
echo "<hr>";
解释:
1、利用php来实现单链表,php实现算法的实例较为少,后续慢慢补充。
2、目前实现并未考虑时间复杂度和空间复杂度,只是单纯的先实现,后优化。
3、欢迎大佬进行批评指教。
后续:
1、优化代码
2、补充插入