PHP数据结构之实现单链表
学习PHP中,学习完语法,开始尝试实现数据结构,今天实现单链表
<?php
class node //节点的数据结构
{
public $id;
public $name;
public $next;
public function __construct($id,$name) //构造函数
{
$this->id=$id;
$this->name=$name;
$this->next=null;
}
}
class linklist //链表的数据结构
{
private $header;
public function __construct() //链表构造函数
{
$this->header=new node($id=null,$name=null);
}
public function add($node) //向链表中添加节点的函数
{
$current=$this->header;
while($current->next!=null)
{
if($current->id>$node->id)
break;
else if($current->next==$node->id)
{
exit('already exist!');
}
$current=$current->next;
}
$node->next=$current->next;
$current->next=$node;
}
public function del($id) //在链表中删除一个节点
{
$current=$this->header;
$flag=false;
while($current->next!=null)
{
if($current->next->id==$id)
{
$flag=true;
break;
}
$current=$current->next;
}
if($flag)
$current->next=$current->next->next;
else
echo "can not find the node which id=".$id;
}
public function getlength() //获取链表的长度
{
$current=$this->header;
$i=0;
while($current->next!=null)
{
$i++;
$current=$current->next;
}
return $i;
}
public function getlist() //获取整个链表
{
$current=$this->header;
if($current->next==null)
{
echo "empty list"; //空表
return;
}
while($current->next!=null)
{
echo "id=".$current->next->id." , "."name=".$current->next->name."<br>";
if($current->next->next==null)
break;
$current=$current->next;
}
}
public function update($id,$name) //更新表
{
$current=$this->header;
if($current->next==null)
exit("empty list");
while($current->next!=null)
{
if($current->id==$id)
break;
$current=$current->next;
}
return $current->name=$name;
}
}
$list=new linklist(); //构造一个表
$list->add(new node(1,'aaa'));
$list->add(new node(2,'bbb'));
$list->add(new node(3,'ccc'));
$list->add(new node(4,'ddd'));
$list->add(new node(5,'eee'));
$list->add(new node(6,'fff'));
$list->add(new node(7,'ggg'));
$list->add(new node(8,'hhh'));
$list->add(new node(9,'iii'));
$list->getlist();
echo"<br/> the length is ".$list->getlength()."<br/>";
echo"测试删除节点<br/>";
$list->del('8');
$list->getlist();
echo"测试更新节点<br/>";
$list->update('9','AAA');
$list->getlist();
?>
输出结果为:
id=1 , name=aaa
id=2 , name=bbb
id=3 , name=ccc
id=4 , name=ddd
id=5 , name=eee
id=6 , name=fff
id=7 , name=ggg
id=8 , name=hhh
id=9 , name=iii
the length is 9
测试删除节点
id=1 , name=aaa
id=2 , name=bbb
id=3 , name=ccc
id=4 , name=ddd
id=5 , name=eee
id=6 , name=fff
id=7 , name=ggg
id=9 , name=iii
测试更新节点
id=1 , name=aaa
id=2 , name=bbb
id=3 , name=ccc
id=4 , name=ddd
id=5 , name=eee
id=6 , name=fff
id=7 , name=ggg
id=9 , name=AAA