Created
July 23, 2014 05:31
-
-
Save jonfriesen/42a5add7d04a410b6d9f to your computer and use it in GitHub Desktop.
PHP Linked List
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
<!-- | |
Filename: linkedlist.php | |
Creation Date: July 22, 2014 | |
Purpose: Create a basic linked list | |
--> | |
<?php | |
class Node | |
{ | |
private $object; | |
private $next; | |
function __construct($object) | |
{ | |
$this->setObject($object); | |
$this->setNext(null); | |
} | |
function setObject($object) | |
{ | |
$this->object = $object; | |
} | |
function getObject(){ | |
return $this->object; | |
} | |
function setNext($next) | |
{ | |
$this->next = $next; | |
} | |
function getNext() | |
{ | |
return $this->next; | |
} | |
} | |
class LinkedList | |
{ | |
public $firstNode; | |
public $currentNode; | |
public $count; | |
function __construct() | |
{ | |
$this->firstNode = null; | |
$this->currentNode = null; | |
$this->count = 0; | |
} | |
function insertObject($object) | |
{ | |
$node = new Node($object); | |
if($this->firstNode == null) | |
$this->firstNode = $node; | |
if($this->currentNode == null) | |
$this->currentNode = $node; | |
$this->currentNode->setNext($node); | |
$this->currentNode = $node; | |
$this->count++; | |
} | |
function outputList() | |
{ | |
$list = array(); | |
$current = $this->firstNode; | |
while($current != null) { | |
array_push($list, $current->getObject()); | |
$current = $current->getNext(); | |
} | |
foreach($list as $l) | |
{ | |
echo $l.' '; | |
} | |
} | |
} | |
$list = new LinkedList(); | |
$list->insertObject("Hello"); | |
$list->insertObject("World!"); | |
$list->insertObject("My"); | |
$list->insertObject("Name"); | |
$list->insertObject("Is"); | |
$list->insertObject("Jon."); | |
$list->outputList(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment