Skip to content

Instantly share code, notes, and snippets.

@KerryJones
Last active December 4, 2015 06:47
Show Gist options
  • Save KerryJones/370812a00118e646a803 to your computer and use it in GitHub Desktop.
Save KerryJones/370812a00118e646a803 to your computer and use it in GitHub Desktop.
PHP Data Structure: Linked List
class LinkedList {
public $head;
public function add($data) {
$new_node = new Node($data);
if ( is_null( $this->head ) ) {
$this->head = $new_node;
} else
{
$node = $this->head;
while (!is_null($node->next))
{
$node = $node->next;
}
$node->next = $new_node;
}
return $new_node;
}
public function delete($data) {
if ( $this->head->data == $data ) {
$this->head = $this->head->next;
} else {
$node = $this->head;
while( !is_null($node->next) ) {
if ( $node->next->data == $data ) {
$node->next = $node->next->next;
break;
}
$node = $node->next;
}
}
}
}
class Node {
public $data;
public $next;
public function __construct($data) {
$this->data = $data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment