php链表创建和遍历

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

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值