面试必备
<?php
define("OK",true);
define("ERROR",false);
class node
{
public $next;
public $data;
}
function InitList(&$L): bool
{
$L= new node();
$L->next=NULL;
return OK;
}
function ListEmpty($L): bool
{
if($L->next)
return FALSE;
else
return TRUE;
}
function ClearList($L): bool
{
$p=$L->next;
while($p)
{
$q=$p->next;
unset($p);
$p=$q;
}
$L->next=NULL;
return OK;
}
function ListTraverse($L): bool
{
$p = $L->next;
while ($p) {
visit($p->data);
$p = $p->next;
}
printf("\n");
return OK;
}
function visit($data): bool
{
printf("%d ", $data);
return OK;
}
function ListLength(&$L): int
{
$i=0;
$p=$L->next;
while($p)
{
$i++;
$p=$p->next;
}
return $i;
}
function ListInsert(&$L, int $i, $e): bool
{
$p = $L;
$j = 1;
while ($p && $j < $i) {
$p = $p->next;
++$j;
}
if (!$p || $j > $i)
return ERROR;
$s = new node();
$s->data = $e;
$s->next = $p->next;
$p->next = $s;
return OK;
}
function ListDelete($L,int $i,node $e): bool
{
$p = $L;
$j = 1;
while ($p->next && $j < $i)
{
$p = $p->next;
++$j;
}
if (!($p->next) || $j > $i)
return ERROR;
$q = $p->next;
$p->next = $q->next;
$e = $q->data;
unset($q);
return OK;
}
$node = null;
InitList($node);
for ($j = 1; $j <= 5; $j++)
$i = ListInsert($node, 1, $j);
ListTraverse($node);
$e = new node();
ListDelete($node,5,$e);
printf("删除第%d个的元素值为:%d\n",5,$e);
ListTraverse($node);
ClearList($node);