How to implement doubly linked list in PHP?

You need to be keeping track of $prev and $next on the elements, not the list. If you want to make it transparent, you can wrap each element in a bean that has pointers to the next and previous ones, or just make element have 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 the element (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.

class DoublyLinkedList {
    private $start = null;
    private $end = null;

    public function add(Element $element) {
        //if this is the first element we've added, we need to set the start
        //and end to this one element
        if($this->start === null) {
            $this->start = $element;
            $this->end = $element;
            return;
        }

        //there were elements already, so we need to point the end of our list
        //to this new element and make the new one the end
        $this->end->setNext($element);
        $element->setPrevious($this->end);
        $this->end = $element;
    }

    public function getStart() {
        return $this->start;
    }

    public function getEnd() {
        return $this->end;
    }
}

class Element {
    private $prev;
    private $next;
    private $data;

    public function __construct($data) {
        $this->data = $data;
    }

    public function setPrevious(Element $element) {
        $this->prev = $element;
    }

    public function setNext(Element $element) {
        $this->next = $element;
    }

    public function setData($data) {
        $this->data = $data;
    }
}

There are, of course, other methods you could add; and if anyone is interested in those I can add them as well.


Before coding anything, tell them it's already been done and is included in the PHP standard library. http://php.net/manual/en/class.spldoublylinkedlist.php


Also, your add function shouldn't take an element. It should just be $list->add('a'); You are exposing your implementation too much.