本示例详细解析了使用PHP语言构建双向链表并进行节点插入与删除的具体实现方案,旨在为开发者提供实用的参考代码。
双向链表基本概念与特性
概念简介:
双向链表(亦称双链表)作为链表的一种变体,其核心特征在于每个数据结点内部维护了两个指针域,分别用于指向当前结点的直接后继结点和直接前驱结点。这一结构使得程序能够从链表中的任意位置出发,便捷地向前或向后遍历访问相邻结点。在实际工程应用中,通常建议构造双向循环链表以优化边界处理。
PHP双向链表节点增删代码实现
具体代码实现如下:
<?php
class node{
public $prev;
public $next;
public $data;
public function __construct($data,$prev=null,$next=null){
$this->data=$data;
$this->prev=$prev;
$this->next=$next;
}
}
class doubleLinkList{
private $head;
public function __construct()
{
$this->head=new node("head",null,null);
}
//插入节点
public function insertLink($data){
$p=new node($data,null,null);
$q=$this->head->next;
$r=$this->head;
while($q){
if($q->data>$data){
$q->prev->next=$p;
$p->prev=$q->prev;
$p->next=$q;
$q->prev=$p;
}else{
$r=$q;$q=$q->next;
}
}
if($q==null){
$r->next=$p;
$p->prev=$r;
}
}
//从头输出节点
public function printFromFront(){
$p=$this->head->next;
$string="";
while($p){
$string.=$string?",":"";
$string.=$p->data;
$p=$p->next;
}
echo $string."
";
}
//从尾输出节点
public function printFromEnd(){
$p=$this->head->next;
$r=$this->head;
while($p){
$r=$p;$p=$p->next;
}
$string="";
while($r){
$string.=$string?",":"";
$string.=$r->data;
$r=$r->prev;
}
echo $string."
";
}
public function delLink($data){
$p=$this->head->next;
if(!$p)
return;
while($p){
if($p->data==$data)
{
$p->next->prev=$p->prev;
$p->prev->next=$p->next;
unset($p);
return;
}
else{
$p=$p->next;
}
}
if($p==null)
echo "没有值为{$data}的节点";
}
}
$link=new doubleLinkList();
$link->insertLink(1);
$link->insertLink(2);
$link->insertLink(3);
$link->insertLink(4);
$link->insertLink(5);
$link->delLink(3);
$link->printFromFront();
$link->printFromEnd();
$link->delLink(6);
程序执行输出结果:
1,2,4,5
5,4,2,1,head
没有值为6的节点
期望上述关于PHP双向链表操作的解析能为各位在程序设计过程中提供有益的帮助。