Over a million developers have joined DZone.

Construct a Sorted PHP Linked List

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

This is really a draft, but I somehow decided to post it. Here’s a simple linked list in PHP, where only the add() method is slightly different. When you have an item to add it’s placed on the “right” place – the result is a sorted list.

Few notes before the code! This list is designed for integers, but I plan to “extend” it somehow and it can be improved a lot. In my future posts I’ll post something more about the complexity of the algorithm and an analysis of it.

class Node
    public $data;
    public $next;
    public $prev;
    public function __construct($data, $prev, $next)
        $this->data = $data;
        $this->prev = $prev;
        $this->next = $next;
class LinkedList
    protected $front = null;
    public function add($data)
        if (!$this->front) {
            $node = new Node($data, null, null);
            $this->front = &$node;
        } else {
            if ($data < $this->front->data) {
                $node = new Node($data, null, $this->front);
                $this->front = $node;
            $current = $this->front;
            while ($current) {
                if ($current->data < $data && isset($current->next) && $current->next->data > $data) {
                    $node = new Node($data, $current, $current->next);
                    $current->next = $node;
                if ($current->data < $data && !isset($current->next)) {
                    $node = new Node($data, $current, $current->next);
                    $current->next = $node;
                $current = $current->next;
    public function printl()
        $current = &$this->front;
        while($current) {
            echo $current->data, '<br />';
            $current = $current->next;
$list = new LinkedList();


Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Stoimen Popov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}