Skip to content

Instantly share code, notes, and snippets.

@jonfriesen
Created July 23, 2014 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonfriesen/42a5add7d04a410b6d9f to your computer and use it in GitHub Desktop.
Save jonfriesen/42a5add7d04a410b6d9f to your computer and use it in GitHub Desktop.
PHP Linked List
<!--
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