Skip to content

Instantly share code, notes, and snippets.

@kapolos
Created September 8, 2015 12:40
Show Gist options
  • Save kapolos/3fd0944c4b62c509ce9e to your computer and use it in GitHub Desktop.
Save kapolos/3fd0944c4b62c509ce9e to your computer and use it in GitHub Desktop.
<?php
class SingleLinkedListNode
{
public $value, $next;
public function __construct($value = NULL)
{
$this->value = $value;
}
}
/**
* Removes a node from a single linked list
*
* @param \SingleLinkedListNode $node
*
* @return bool Returns false if the node is the tail, true otherwise
*/
function removeNode(SingleLinkedListNode $node)
{
if (!$node->next) {
return FALSE;
}
$node->value = $node->next->value;
$node->next = $node->next->next;
return TRUE;
}
/* Usage */
// Handcraft a linked list
$nodes = [];
foreach (range(5, 1, -1) as $val) {
$node = new SingleLinkedListNode($val);
if ($val !== 5) {
$node->value = $val;
$node->next = $nodes[$val + 1];
}
$nodes[$val] = $node;
}
extract($nodes, EXTR_PREFIX_ALL, 'node');
// Now we have 1 -> 2 -> 3 -> 4 -> 5
// with nodes in variables named $node_1, $node_2, etc.
// Remove a node
removeNode($node_3);
// Let's traverse the list
$node = $node_1;
do {
echo $node->value;
if ($node->next) {
echo ' -> ';
$node = $node->next;
} else {
break;
}
} while (TRUE);
/*
1 -> 2 -> 4 -> 5
Congratulations :)
$node_2 has value of 2 and points to $node_3
$node_3 has value of **4** and points to **$node_5**
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment