Created
March 16, 2015 17:05
-
-
Save alnorris/744fb975018537a8bafe to your computer and use it in GitHub Desktop.
Linked List in PHP
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 | |
class node { | |
public $data; | |
public $nextNode; | |
public function __construct($data, $nextNode) { | |
$this->data = $data; | |
$this->nextNode = $nextNode; | |
} | |
} | |
class LinkedList { | |
public $firstNode; | |
public function __construct($data) { | |
$this->firstNode = new node($data, null); | |
} | |
function addNode($data) { | |
// find last node | |
$lastnode = $this->firstNode; | |
while($lastnode->nextNode != null) { | |
$lastnode = $lastnode->nextNode; | |
} | |
$newNode = new node($data, null); | |
$lastnode->nextNode = $newNode; | |
} | |
function traverseList() { | |
$nextNode = $this->firstNode; | |
while($nextNode->nextNode != null) { | |
// print "lol"; | |
print $nextNode->data; | |
print "\n"; | |
$nextNode = $nextNode->nextNode; | |
} | |
} | |
} | |
$list = new LinkedList("lol"); | |
$list->addNode("haha"); | |
$list->addNode("yaya"); | |
$list->addNode("foo"); | |
$list->traverselist(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment