Skip to content

Instantly share code, notes, and snippets.

@chadyred
Last active September 11, 2024 17:59
Show Gist options
  • Save chadyred/078a3a1d03388c9ae8c2248e63e872c5 to your computer and use it in GitHub Desktop.
Save chadyred/078a3a1d03388c9ae8c2248e63e872c5 to your computer and use it in GitHub Desktop.
LinkedList draft
<?php
class Node
{
private ?Node $next;
public function __construct(public readonly string $value)
{
$this->next = null;
}
public function value(): string
{
return $this->value;
}
public function next(): ?Node
{
return $this->next;
}
public function setNext(Node $node): self
{
$this->next = $node;
return $this;
}
}
class LinkedList implements Iterator
{
/**
* @var array<Node>
*/
public array $elements;
private int $key;
private ?Node $current;
private Node $last;
private Node $first;
private int $nbElement;
/**
* @param string[] $arrayOfString
*/
public function __construct(array $arrayOfString)
{
$this->elements = [];
$initialIndex = 0;
$this->key = $initialIndex;
$this->nbElement = count($arrayOfString); // Project this counter here is the most optimized instead of retrieve the real "lenght" of the first node...which containe all the next nodes
$previousNode = null;
foreach ($arrayOfString as $key => $elt) {
$node = new Node($elt);
if ($key === array_key_first($arrayOfString)) {
$this->first = $node;
} else {
if ($key === array_key_last($arrayOfString)) {
$this->last = $node;
}
$previousNode->setNext($node);
$this->elements[] = $previousNode;
}
$previousNode = $node;
}
}
public function head(): Node
{
return $this->first;
}
public function tail(): Node
{
return $this->last;
}
public function current(): mixed
{
if ($this->key === 0) {
$this->current = $this->head(); // HEAD IS THE ONLY ONE AT THE FIRST TIME TO CONTAIN AND HAVE EZACH INFORMATION OF EACH NEXT
} else {
$this->current = $this->current->next();
}
return $this->current;
}
public function next(): void
{
$this->key++;
}
public function key(): mixed
{
return $this->key;
}
public function valid(): bool
{
return $this->key >= 0 && $this->key < $this->nbElement;
}
public function rewind(): void
{
$this->key = 0;
}
}
$linkedList = new LinkedList(['A', 'B', 'C']);
foreach ($linkedList as $elt) {
var_dump($elt->value());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment