More useless PHP – Inplace Reverse
Code
<?php
/*
PHP implementation of a common programming problem:
Reversing a singly linked list
*/
error_reporting(E_ALL | E_STRICT);
// This is our basic node
class WordNode
{
public $word;
public $nextNode;
public function __construct($word = null)
{
$this->word = $word;
}
// Print all content of this node, and linked nodes
public function __toString($separator = '')
{
$buffer = '';
$current = $this;
do
{
// Append the separator as long as there is a next node
$buffer .= $current->word . (($current->nextNode !== null) ? $separator : '');
}
while(($current = $current->nextNode) !== null);
return $buffer;
}
}
// Takes an array and turns it into a linked list
// (Remember this is purely an academic exercise :-)
function buildWordNodeList($sourceArray)
{
// First step create the linked list
$firstNode = new WordNode($sourceArray[0]);
$lastNode = $firstNode;
foreach(array_slice($sourceArray, 1) as $word)
{
$thisNode = new WordNode($word);
$lastNode->nextNode = $thisNode;
$lastNode = $thisNode;
}
return $firstNode;
}
// Inplace reverse
function reverseWordNodeListInplace(WordNode &$head)
{
// Init the loop by separating the top node, and
// keeping track of what is left ($tail)
$tail = $head->nextNode;
// This is set to null as it will end up being the
// last node and shouldn't point anywhere
$head->nextNode = null;
while($tail !== null)
{
// Take the next node, and seperate it, and again
// keep track of what's left
$next = $tail;
$tail = $next->nextNode;
// Now make this node the parent of the previous top node
$next->nextNode = $head;
// This node is now at the top
$head = $next;
}
}
$list = buildWordNodeList(array("a","b","c","d","e","f","g","h", "i", "j", "k"));
echo $list . "\n";
reverseWordNodeListInplace($list);
echo $list . "\n";
reverseWordNodeListInplace($list);
echo $list . "\n";
echo $list->__toString(" ") . "\n";
?>
Output
abcdefghijk
kjihgfedcba
abcdefghijk
a b c d e f g h i j k