user3576185
user3576185

Reputation: 11

Recursive Functions and linked lists PHP

I was given a quiz by an employer to determine my ability as a programmer and the test was more or less "Write a function that counts the length of this linked list". I failed the quiz because for whatever reason my function didn't return anything (It was a timed quiz). This is my code.

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;
    }

}

in getListLength im getting 3 when i print count before the return statement. But after the function returns I'm left with no output. I feel really stupid right now. Any thoughts?

Upvotes: 0

Views: 206

Answers (3)

Henrique Barcelos
Henrique Barcelos

Reputation: 7900

Assuming this is the code from the quiz (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;

I don't think you need recursion to solve that. You could just:

function getListLength($list) {
    $count = 0;
    $item = $list;

    while($item instanceof IntList) {
        $count++;
        $item = $item->next;
    }

    return $count;
}

Upvotes: 1

Don't Panic
Don't Panic

Reputation: 41810

Since you are trying to use recursion here, I think the only thing that is missing is that your recursive case is not returning. You really should not need global. If you need to start at zero, you can give your getListLength a default count, or explicitly call it with zero in 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;
    }
}

Upvotes: 0

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

You just forgot to put global $count; in the second function.

Also, if you want to count the last one, you should move the $count++ outside of the conditional.

Here's a fiddle.

Alternatively, you can pass the $count variable by reference

function getListLength($L, &$count){...}

Another fiddle..

Upvotes: 0

Related Questions