Skip to content

Instantly share code, notes, and snippets.

@rmruano
Last active March 1, 2021 07:33
Show Gist options
  • Select an option

  • Save rmruano/c3cfc44faa22463325f913d7cc4b02e9 to your computer and use it in GitHub Desktop.

Select an option

Save rmruano/c3cfc44faa22463325f913d7cc4b02e9 to your computer and use it in GitHub Desktop.
Simple iterable linked list storing keyvalues. No removal implemented for simplicity. Easy & fast removal could be implemented with a Double Linked List approach. Requires PHP 7.4 (typed properties)
<?php
class LinkedNode {
protected LinkedNode $next;
protected $value;
protected string $key;
public function __construct(string $key, $value) {
$this->value = $value;
$this->key = $key;
}
public function key(): string {
return $this->key;
}
public function value() {
return $this->value;
}
public function next(): ?LinkedNode {
return $this->next ?? null;
}
public function add(LinkedNode $node): LinkedNode {
$this->next = $node;
return $this;
}
}
class LinkedList implements Iterator {
protected LinkedNode $firstNode;
protected LinkedNode $lastNode;
protected ?LinkedNode $iteratorCurrentNode;
public function dump() {
foreach($this as $node) {
echo "[" . $node->key().":".$node->value() . "] -> ";
}
echo "END".PHP_EOL;
}
public function dumpKeys() {
foreach($this as $node) {
echo "[" . $node->key()."] -> ";
}
echo "END".PHP_EOL;
}
public function get(string $key): ?LinkedNode {
foreach($this as $node) {
if ($node->key()===$key) return $node;
}
return null;
}
public function add(LinkedNode $node): LinkedList {
if (isset($this->lastNode)) $this->lastNode->add($node);
$this->lastNode = $node;
if (!isset($this->firstNode)) $this->firstNode = $node;
if (!isset($this->iteratorCurrentNode)) $this->iteratorCurrentNode = $this->firstNode;
return $this;
}
public function next() {
if (isset($this->iteratorCurrentNode) && $this->iteratorCurrentNode->next()) {
$this->iteratorCurrentNode = $this->iteratorCurrentNode->next();
} else {
$this->iteratorCurrentNode = null;
}
}
public function current(): ?LinkedNode {
return $this->iteratorCurrentNode;
}
public function rewind() {
$this->iteratorCurrentNode = $this->firstNode;
}
public function key(): ?string {
return $this->iteratorCurrentNode->key() ?? null;
}
public function valid() {
return $this->iteratorCurrentNode!=null;
}
}
$linkedList = new LinkedList();
$linkedList->add(new LinkedNode("node-1", "Node value 1"));
$linkedList->add(new LinkedNode("node-2", "Node value 2"));
$linkedList->add(new LinkedNode("node-3", "Node value 3"));
$linkedList->dumpKeys();
echo "Value of node-2: ". ($linkedList->get("node-2")->value() ?? null) . PHP_EOL;
// EXPECTED OUTPUT ---------------
// [node-1] -> [node-2] -> [node-3] -> END
// Value of node-2: Node value 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment