Skip to content

Instantly share code, notes, and snippets.

@alnorris
Created March 16, 2015 17:05
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 alnorris/744fb975018537a8bafe to your computer and use it in GitHub Desktop.
Save alnorris/744fb975018537a8bafe to your computer and use it in GitHub Desktop.
Linked List in PHP
<?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