一位雇主给我做了一个测试,以确定我作为程序员的能力,测试或多或少是"写一个计算这个链表长度的函数"。我没有通过测试,因为无论出于什么原因,我的函数都没有返回任何内容(这是一个定时测试)。这是我的密码。
class IntList{
var $value = 1;
var $next = null;
}
$A = new IntList();
$B = new IntList();
$C = new IntList();
$D = new IntList();
$A->next = $B;
$B->next = $C;
$C->next = $D;
main($A);
$count = 0;
function main($L)
{
global $count;
$final = getListLength($L, $count);
print $final;
}
function getListLength($L, $count)
{
if (isset($L->next))
{
$count++;
getListLength($L->next, $count);
} else
{
print $count;
return $count;
}
}
在getListLength中,当我在return语句之前打印count时,im得到3。但在函数返回后,我就没有输出了。我现在觉得自己真的很愚蠢。有什么想法吗?
假设这是测试中的代码(argh,PHP4--'):
class IntList{
var $value = 1;
var $next = null;
}
$A = new IntList();
$B = new IntList();
$C = new IntList();
$D = new IntList();
$A->next = $B;
$B->next = $C;
$C->next = $D;
我不认为你需要递归来解决这个问题。你可以:
function getListLength($list) {
$count = 0;
$item = $list;
while($item instanceof IntList) {
$count++;
$item = $item->next;
}
return $count;
}
您刚刚忘记将global $count;
放在第二个函数中。
此外,如果要计算最后一个,则应将$count++
移到条件之外。
这是一把小提琴。
或者,您可以通过引用传递$count变量
function getListLength($L, &$count){...}
又是一把小提琴。。
由于您试图在这里使用递归,我认为唯一缺少的是您的递归用例没有返回。你真的不需要全球化。如果需要从零开始,可以给getListLength
一个默认计数,或者在main
中用零显式调用它。
function main($L) {
$final = getListLength($L);
print $final;
}
function getListLength($L, $count = 0) {
if (isset($L->next)) {
$count++;
// this case should return
return getListLength($L->next, $count);
} else {
return $count;
}
}