Last active
November 28, 2018 14:47
-
-
Save vegasje/8679653 to your computer and use it in GitHub Desktop.
Demonstration of a PHP LinkedList, as well as a LinkedListIterator that implements \Iterator.
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 LinkedList { | |
private $data; | |
private $next; | |
private function __construct() {} | |
public static function fromArray($array) { | |
$head = new LinkedList(); | |
$head->data = $array[0]; | |
$previous = $head; | |
$array = array_slice($array, 1); | |
foreach ($array as $item) { | |
$current = new LinkedList(); | |
$current->data = $item; | |
$previous->next = $current; | |
$previous = $current; | |
} | |
return $head; | |
} | |
public function data() { return $this->data; } | |
public function next() { return $this->next; } | |
public function reverse() { | |
$current = new LinkedList(); | |
$current->data = $this->data; | |
$next = $this->next; | |
while ($next !== null) { | |
$prior = new LinkedList(); | |
$prior->data = $next->data; | |
$prior->next = $current; | |
$current = $prior; | |
$next = $next->next; | |
} | |
return $prior; | |
} | |
public function iterator() { | |
return LinkedListIterator::fromLinkedList($this); | |
} | |
} | |
class LinkedListIterator implements \Iterator { | |
private $head; | |
private $current; | |
private $key; | |
private function __construct() {} | |
public static function fromLinkedList($linkedList) { | |
$lli = new LinkedListIterator(); | |
$lli->head = $linkedList; | |
$lli->current = $linkedList; | |
$lli->key = 0; | |
return $lli; | |
} | |
public function current() { | |
return $this->current->data(); | |
} | |
public function key() { | |
return $this->key; | |
} | |
public function next() { | |
$this->current = $this->current->next(); | |
$this->key += 1; | |
} | |
public function rewind() { | |
$this->current = $this->head; | |
$this->key = 0; | |
} | |
public function valid() { | |
return $this->current !== null; | |
} | |
} | |
$ll = LinkedList::fromArray(array(1, 2, 3, 4)); | |
$lli = $ll->iterator(); | |
foreach ($lli as $i) { | |
echo("{$i}\n"); | |
} | |
$ll = $ll->reverse(); | |
$lli = $ll->iterator(); | |
foreach ($lli as $i) { | |
echo("{$i}\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment