<?php
/**
* 链表节点
*/
class ListNode
{
public $val;
public $next;
public function __construct( $val = null, $next = null )
{
$this->val = $val;
$this->next = $next;
}
}
/**
* 链表
*/
class LinkList {
public $val = null;
public $next = null;
/**
* 尾插
*/
public function add($value){
if($this->val == null ){
$this->val = $value;
}else{
$obj = $this;
while (isset($obj->next)) {
$obj = $obj->next;
}
if(!isset($obj->next)){
$next = new ListNode();
$next->val = $value;
$obj->next = $next;
}
}
}
/**
* 数组转队列
*/
public static function arrayToList($data){
$obj = new LinkList();
foreach ($data as $key => $value) {
$obj->add($value);
}
return $obj;
}
}
$obj = new LinkList();
$obj->add(1);
$obj->add(2);
$obj->add(3);
$arr1 = [1,2,3];
$l1 = LinkList::arrayToList($arr1);
php 实现单链表 刷题用 无head
最新推荐文章于 2024-08-24 17:46:18 发布