//单链表的存储结构
class Node{
public $data;//数据域
public $next;//指针域 指向下一个结点
function __construct(){
$this->data = null;
$this->next = null;
}
}
//单链表数据类型
class LinkList{
public $data;
public $next;
function __construct(){
$this->data = null;
$this->next = null;
}
//头插法创建整个单链表
public function CreateListHead($arr){
if (is_array($arr)){
foreach($arr as $value){
$p = new Node();
$p->data = $value;
$p->next = $this->next;
$this->next = $p;
}
} else {
return 'false';
}
}
//尾插法创建整个单链表
public function CreateListTail(array $arr){
$r = $this; //记录末尾结点
foreach ($arr as $value){
$p = new Node();
$p->data = $value;
$r->next = $p;
$r = $p;
}
$r->next = null;
}
//单链表的整表删除
public function ClearList(){
$p = $this->next;
while ($p) {
$q = $p->next;
unset($p);
$p = $q;
}
$this->next = null;
return 'ok';
}
//获取第i个结点值
public function GetElem($i){
$p = $this->next;
$j = 1;
while($p && $j < $i){
$p = $p->next;
++$j;
}
if(!$p || $j > $i){
return 'error';
}
return $p->data;
}
//删除第i个结点
public function ListDelete($i){
$j = 1;
$p = $this;
while ($p->next && $j < $i){
$p = $p->next;
++$j;
}
if(!($p->next) || $j > $i){
return 'error';
}
$q = $p->next;
$p->next = $q->next;
unset($q);
return 'ok';
}
//第i个节点前插入数据值为value的节点
public function ListInsert($i, $value){
$j = 1;
$p = $this;
while($p && $j < $i){
$p = $p->next;
++$j;
}
if(!$p || $j > $i){
return 'error';
}
$s = new Node();
$s->data = $value;
$s->next = $p->next;
$p->next = $s;
return 'ok';
}
}