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."
";

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"
the length is ".$list->getlength()."
";

echo"测试删除节点
";

$list->del(‘8‘);

$list->getlist();

echo"测试更新节点
";

$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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值