<?php
// 单项链表
// 定义类用来存储运行时的信息
class Node
{
public $id;
public $name;
// 指针域
public $next;
public function __construct($id = null, $name = null)
{
$this->id = $id;
$this->name = $name;
$this->next = null;
}
}
class ListNode
{
// 定义头结点
public $header;
public function __construct($id = null, $name = null)
{
$this->header = new Node($id, $name);
}
// 添加一个节点,
public function addList($node) {
// 讲当前链表复制到改变量中
$current = $this->header;
// 判断如果不为空,同时处理成一个有序的链表
while($current->next != null) {
// 判断当前已有的节点ID是否大于要加入的节点ID,如果大于则break
if($current->next->id > $node->id)
{
break;
}
// 讲节点指针更新为下一个节点。直到满足条件后跳出循环
$current = $current->next;
}
// 将要加入的指针 指向到目前的指针指向
$node->next = $current->next;
// 将当前的指针 指向要加入的信息
$current->next = $node;
}
// 获取链表长度
public function getList() {
$current = $this->header;
$num = 0;
while($current->next != null) {
$num ++;
$current = $current->next;
}
return $num;
}
}
$listNode = new ListNode();
$listNode->addList(new Node(2, "test2"));
$listNode->addList(new Node(1, "test1"));
$listNode->addList(new Node(5, "test1"));
$listNode->addList(new Node(6, "test1"));
$num = $listNode->getList();
print_r($listNode);
echo "链表长度, ". $num . "\n";
/**
* 比较关键的问题,
* 1. 链表是在内存中申请一个节点信息,如果有多个信息,则挨个申请,
* 2. 链表中最关键的是指针域,在我理解,就是将一个object对象,指向到一个新的object对象,每个对象中的变量保持一直。
* 3. 在内存中需要单独申请一片空间来管理指针域
* 4. 获取链表信息,在单项链表中,只能从节点头部开始,挨个循环遍历,无法向数组那样随存随取。
*/
php实现单项有序链表
最新推荐文章于 2022-06-30 17:25:04 发布