I got an interview question on Friday and I think I flunked it. The question was:
Write a class that process a double linked list in PHP.
I understand the concept, and here’s the code I gave:
class element {
private $current;
public function __construct($e) {
$this->current = $e;
}
// method
// etc..
}
class doublelist
{
private $prev;
private $next;
private $current;
private $list;
public function add(element $e) {
if($this->current == NULL) {
$this->prev = $this->current;
}
$this->current = $e;
}
}
$list = new doublelist();
$list->add(new element('a'));
$list->add(new element('b'));
This works initially, but if I add a second element I “lose” the first one, and I don’t understand why.
You need to be keeping track of
$prevand$nexton theelements, not the list. If you want to make it transparent, you can wrap eachelementin a bean that has pointers to the next and previous ones, or just makeelementhave those by definition.The way you’re doing it right now, the list will only know which one is the current
element, and which one came before that. But what you should really be doing is figuring it out from theelement(or bean) which one will be the next or previous.Edit
Since this question has been getting the occasional view, I thought I’d add a little code to help explain this better.
There are, of course, other methods you could add; and if anyone is interested in those I can add them as well.