Skip to content

Instantly share code, notes, and snippets.

@sergiors
Created January 21, 2016 22:40
Show Gist options
  • Save sergiors/174cca8292745bf3f2be to your computer and use it in GitHub Desktop.
Save sergiors/174cca8292745bf3f2be to your computer and use it in GitHub Desktop.
<?php

use Sergiors\LinkedList\LinkedList;

$list = new LinkedList();
$list->push(1);
$list->push(2);
$list->push(3);
$list->push(4);

while ($list->count()) {
    var_dump($list->shift());
}
<?php
namespace Sergiors\LinkedList;
class LinkedList
{
private $firstNode;
private $lastNode;
private $totalNodes;
public function isEmpty()
{
return null === $this->firstNode
&& null === $this->lastNode;
}
public function count()
{
return $this->totalNodes;
}
public function push($value)
{
$this->totalNodes++;
$node = new Node($value);
if ($this->isEmpty()) {
$this->firstNode = $node;
} else {
$this->lastNode->setNext($node);
}
$this->lastNode = $node;
}
public function shift()
{
$this->totalNodes--;
$tmpNode = $this->firstNode;
$this->firstNode = $tmpNode->getNext();
return $tmpNode->getValue();
}
}
<?php
namespace Sergiors\LinkedList;
class Node
{
private $value;
private $nextNode;
public function __construct($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
public function getNext()
{
return $this->nextNode;
}
public function setNext(Node $next)
{
$this->nextNode = $next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment