PHP数据结构
单链表
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020-08-15
* Time: 16:32
*/
class Node
{
public $data;
public $next;
public function __construct($data, $next)
{
$this->data = $data;
$this->next = $next;
}
}
class SingleLink
{
public $head;
public function __construct($arr)
{
$this->head = $this->init($arr);
}
//头插法初始化单链表
private function init($arr)
{
$head = new Node('head', NULL);
foreach ($arr as $vo) {
$node = new Node($vo, $head->next);
$head->next = $node;
}
return $head;
}
//尾插法初始化单链表
private function initTail($arr)
{
$head = new Node('head', NULL);
$tail=$head;
foreach ($arr as $vo) {
$node = new Node($vo,NULL);
$tail->next = $node;
$tail=$node;
}
return $head;
}
//从头插入节点
public function insertHead($node)
{
$node->next = $this->head->next;
$this->head->next = $node;
}
//从尾部插入节点
public function insertTail($node)
{
$p = $this->head;
while ($p->next != NULL) {
$p = $p->next;
}
$p->next = $node;
}
public function deleteNode($data)
{
$p = $this->head;
while ($p->next != null) {
$prev = $p;
$p = $p->next;
if ($p->data == $data) {
$prev->next = $p->next;
$p->next = NULL;
break;
}
}
}
public function echoList()
{
$p = $this->head->next;
$str=' ';
while ($p) {
$str.="{$p->data},";
$p = $p->next;
}
echo substr($str,0,strlen($str)-1).PHP_EOL;
}
}
$sin = new SingleLink(range(2, 5));
$sin->echoList();
$sin->insertHead(new Node(6, NULL));
$sin->echoList();
$sin->insertTail(new Node(1, NULL));
$sin->echoList();
$sin->deleteNode(6);
$sin->echoList();
引用方式实现单链表
function initTail($arr)
{
$head = ['data'=>'head','next'=>NULL];
$p=&$head;
foreach ($arr as $vo) {
$p['next'] = ['data'=>$vo];
$p=&$p['next'];
}
return $head;
}
print_r([initTail([1,2,3,4,5])]);
二叉树
括号表示法创建二叉树,引用数组描述
function createTree($str)
{
$str_arr = str_split($str);
$tree=NULL;
$p = &$tree;
$stack=[];$flag='';
while ($char = array_shift($str_arr)) {
switch ($char) {
case '(':$stack[]=&$p;$flag='left';
break;
case ')':array_pop($stack);
break;
case ',':$flag='right';
break;
default:
if(!$tree){
$p=['data'=>$char];
}else{
$p=&$stack[count($stack)-1];
$p[$flag]=['data'=>$char];
$p= &$p[$flag];
}
break;
}
}
return $tree;
}
print_r(createTree(('A(B(D,E(F,G)),C(H,))')));