<?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());
}
Created
January 21, 2016 22:40
-
-
Save sergiors/174cca8292745bf3f2be to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
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(); | |
} | |
} |
This file contains hidden or 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 | |
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