php中模拟链表和链表的基本操作示例

模拟链表:

name = $name;
$this->id = $id;
}
/**
* 遍历链表
*/
public static function echo_link_list($head) {
$curr = $head;
while ($curr->next != null) {
echo ‘姓名:’.$curr->next->name, ‘ 编号:’.$curr->next->id;
echo ”;
$curr = $curr->next;
}
}
/**
* 添加新节点
*/
public static function add($head, $id, $name) {
$curr = $head;
$obj = new linklist($id, $name);
while ($curr->next != null) {
// 如果当前id < 下一个id,则添加到中间,添加节点到指定顺序位置 if ($curr->next->id > $id) {
$obj->next = $curr->next;
$curr->next = $obj;
return true;
} else if ($curr->next->id == $id) {
echo ‘当前id:’.$id.’重复了,请不要继续添加了!’;
echo ”;
return false;
}
$curr = $curr->next;
}
// 添加节点到尾部
if ($curr->next == null) {
$curr->next = $obj;
}
}
/**
* 删除节点
*/
public static function del($head, $id) {
$curr = $head;
while($curr->next != null) {
if ($curr->next->id == $id) {
$curr->next = $curr->next->next;
return true;
}
$curr = $curr->next;
}
}
/**
* 修改节点
*/
public static function edit($head, $id, $new_name) {
$curr = $head;
while($curr->next != null) {
if ($curr->next->id == $id) {
$curr->next->name = $new_name;
}
$curr = $curr->next;
}
}
}
$head = new linklist();
linklist::add($head, 1, ‘wangdk’);
linklist::add($head, 2, ‘sunshuzhen’);
linklist::add($head, 8, ‘wanghaha’);
linklist::add($head, 6, ‘wangchufen’);
linklist::add($head, 6, ‘wangchufen’);
linklist::add($head, 3, ‘wangdaye’);
linklist::del($head, 1);
linklist::edit($head, 2, ‘hahaha’);
linklist::echo_link_list($head);
?>

链表的增删查改:

name = $name;
$this->id = $id;
}
/**
* 遍历链表
*/
public static function echo_link_list($head) {
$curr = $head;
while ($curr->next != null) {
echo ‘姓名:’.$curr->next->name, ‘ 编号:’.$curr->next->id;
echo ”;
$curr = $curr->next;
}
}
/**
* 添加新节点
*/
public static function add($head, $id, $name) {
$curr = $head;
$obj = new linklist($id, $name);
while ($curr->next != null) {
// 如果当前id < 下一个id,则添加到中间,添加节点到指定顺序位置 if ($curr->next->id > $id) {
$obj->next = $curr->next;
$curr->next = $obj;
return true;
} else if ($curr->next->id == $id) {
echo ‘当前id:’.$id.’重复了,请不要继续添加了!’;
echo ”;
return false;
}
$curr = $curr->next;
}
// 添加节点到尾部
if ($curr->next == null) {
$curr->next = $obj;
}
}
/**
* 删除节点
*/
public static function del($head, $id) {
$curr = $head;
while($curr->next != null) {
if ($curr->next->id == $id) {
$curr->next = $curr->next->next;
return true;
}
$curr = $curr->next;
}
}
/**
* 修改节点
*/
public static function edit($head, $id, $new_name) {
$curr = $head;
while($curr->next != null) {
if ($curr->next->id == $id) {
$curr->next->name = $new_name;
}
$curr = $curr->next;
}
}
}
$head = new linklist();
linklist::add($head, 1, ‘wangdk’);
linklist::add($head, 2, ‘sunshuzhen’);
linklist::add($head, 8, ‘wanghaha’);
linklist::add($head, 6, ‘wangchufen’);
linklist::add($head, 6, ‘wangchufen’);
linklist::add($head, 3, ‘wangdaye’);
linklist::del($head, 1);
linklist::edit($head, 2, ‘hahaha’);
linklist::echo_link_list($head);
?>

以上就介绍了php中模拟链表和链表的基本操作示例,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。

Posted in 未分类