Created
May 28, 2011 11:05
-
-
Save nervetattoo/996792 to your computer and use it in GitHub Desktop.
Linked list in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Item { | |
public $value, $key, $next = null; | |
public function __construct($key, $value) { | |
$this->key = $key; | |
$this->value = $value; | |
} | |
public function next() { | |
return $this->next; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'Item.php'; | |
class LinkedList { | |
protected $items = array(); | |
public $first=null,$last=null; | |
public function append($key, $value) { | |
$item = new Item($key, $value); | |
$this->items[] = $item; | |
if ($this->last) $this->last->next = $item; | |
$this->last = $item; | |
if ($this->first === null) $this->first = $item; | |
return $this; | |
} | |
public function prepend($key, $value) { | |
$item = new Item($key, $value); | |
array_unshift($this->items, $item); | |
if ($this->first) $item->next = $this->first; | |
$this->first = $item; | |
if ($this->last === null) $this->last = $item; | |
return $this; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'LinkedList.php'; | |
class LinkedListTest extends PHPUnit_Framework_TestCase { | |
public function testLinkedList() { | |
$list = new LinkedList; | |
$data = array('foo','bar'); | |
foreach ($data as $k => $v) $list->append($k, $v); | |
$this->assertEquals($data[0], $list->first->value); | |
$this->assertEquals($data[1], $list->last->value); | |
$this->assertNull($list->last->next()); | |
// Prepend data | |
$prepend = array('a','b'); | |
foreach (array_reverse($prepend) as $k => $v) $list->prepend($k, $v); | |
$item = $list->first; | |
foreach (array_merge($prepend, $data) as $value) { | |
$this->assertEquals($value, $item->value); | |
$item = $item->next(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment