当前位置:网站首页>php链表创建和遍历
php链表创建和遍历
2022-07-02 10:55:00 【liuliang514218119】
<?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";
边栏推荐
- P1908 reverse sequence pair
- Use of UIC in QT
- Drawing Nyquist diagram with MATLAB
- The global special paper revenue in 2021 was about $27 million, and it is expected to reach $35 million in 2028. From 2022 to 2028, the CAGR was 3.8%
- Dingtalk send message
- go操作redis
- YOLOv3&YOLOv5输出结果说明
- SystemServer进程
- Solving the longest subsequence with linear DP -- three questions
- selenium的特点
猜你喜欢
Qt入门-制作一个简易的计算器
MySQL45讲——学习极客时间MySQL实战45讲笔记—— 05 | 深入浅出索引(下)
Qt新建项目
The conference on the growth of all things was held in Hangzhou, and dangbei was selected into the top 100 list of future unicorns in China in 2022
每日学习3
QT new project_ MyNotepad++
Analysis of CPU surge in production environment service
[Blue Bridge Cup] children's worship circle
[to be continued] [UE4 notes] l5ue4 model import
selenium,元素操作以及浏览器操作方法
随机推荐
qt中uic的使用
Qt新建项目
Qt如何设置固定大小
[usaco05jan]watchcow s (Euler loop)
Common options of tcpdump command: Three
每天坚持20分钟go的基础二
[to be continued] [UE4 notes] l5ue4 model import
一般来讲,如果频繁出现inconsistent tab and space的报错
Dingtalk 发送消息
Dingtalk send message
[template] longest common subsequence ([DP or greedy] board)
Just 1000 fans, record it
The 29 year old programmer in Shanghai was sentenced to 10 months for "deleting the database and running away" on the day of his resignation!
How to use SAP's metadata framework (MDF) to build custom business rules?
Qt原代码基本知识
代码实现MNLM
693. Travel sequencing (map + topology)
TeamTalk源码分析之win-client
QT new project_ MyNotepad++
Slashgear shares 2021 life changing technology products, which are somewhat unexpected