Here’s a version without the recursive add – so it would use way less memory when adding large data sets as it’s not making endless copies of the data being added to the tree.
<?php
class nodeElement {
public
$data,
$prev=false,
$next=false;
public function __construct($data) {
$this->data=$data;
}
public function show() {
if ($this->prev) $this->prev->show();
echo $this->data,'<br />';
if ($this->next) $this->next->show();
}
}
class nodeTree {
public
$first=false;
public function add($data) {
if ($this->first) {
$current=$this->first;
while (true) {
if (strnatcasecmp($current->data,$data)<0) {
if ($current->next) {
$current=$current->next;
} else {
$current->next=new nodeElement($data);
break;
}
} else {
if ($current->prev) {
$current=$current->prev;
} else {
$current->prev=new nodeElement($data);
break;
}
}
}
} else {
$this->first=new nodeElement($data);
}
}
public function show() {
if ($this->first) {
$this->first->show();
}
}
}
$test=new nodeTree();
$test->add('bravo');
$test->add('charlie');
$test->add('echo');
$test->add('alpha');
$test->add('delta');
$test->show();
?>