<?php
#php链表创建和遍历
/**
* Class node
* 链表节点元素
*/
class node
{
public $item; #当前节点存储元素
public $next; #指向下一个节点的地址
public function __construct($item, $next = null)
{
$this->item = $item;
$this->next = $next;
}
}
$node1 = new node(1);
$node2 = new node(2);
$node3 = new node(3);
$node1->next = $node2;
$node2->next = $node3;
#var_dump($node1);
# 头插法
function create_link_list_head($arr = [])
{
$head = new node($arr[0]); # 头节点
for ($i = 1; $i < count($arr); $i++) {
$node = new node($arr[$i]);
$node->next = $head; #当前节点的下一个节点指向头节点
$head = $node; #当前节点移为头节点
}
return $head;
}
$lk = create_link_list_head([1, 2, 3, 4, 5]);
print_link_list($lk);
echo "\n";
# 遍历打印链表元素
/**
* @param $link_list node
*/
function print_link_list($link_list)
{
while ($link_list) {
print($link_list->item . ",");
$link_list = $link_list->next;
}
}
# 尾插法
function create_link_list_tail($arr = [])
{
$head = new node($arr[0]); # 头节点
$tail = $head; // 尾节点
for ($i = 1; $i < count($arr); $i++) {
$node = new node($arr[$i]);
$tail->next = $node; #尾节点的下一个节点指向当前节点
$tail = $node; #当前节点移为尾节点
}
return $head;
}
$lk = create_link_list_tail([1, 2, 3, 4, 5]);
print_link_list($lk);
echo "\n";
php链表创建和遍历
最新推荐文章于 2023-07-14 09:40:57 发布