<?php
class Node{
public $val;
public $next;
public function __construct( $val = null, $next = null )
{
$this->val = $val;
$this->next = $next;
}
}
class LinkList{
public $head;
public $length;
public function __construct(){
$this->head = new Node();
$this->length = 0;
}
/**
* @param int $val
* 尾部添加元素
*/
public function add(int $val){
$first = new Node();
$first->val = $val;
$show = $this->head;
while ( $show->next != null ){
$show = $show->next;
}
$show->val = $val;
$show->next = $first;
}
/**
* @param int $val
* 头部添加
*/
public function addHead(int $val){
$head = new Node();
$head->val = $val;
$head->next = $this->head;
$this->head = $head;
}
/**
* 展示链表
*/
public function showList(){
$show = $this->head;
echo "<pre>";
print_r($show);
while ( $show->next != null ){
echo $show->val . PHP_EOL;
$show = $show->next;
}
}
}
$a = new LinkList();
$a->add(1);
$a->add(2);
$a->add(3);
$a->addHead(0);
$a->showList();
php 链表
于 2021-11-21 22:15:47 首次发布