Last active
March 14, 2022 16:20
-
-
Save dialyy/de21c838884fad22324cd46f51803e0b to your computer and use it in GitHub Desktop.
php : reverse a linked list
This file contains 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 = null; | |
public $next = null; | |
public function __construct(string $data = null){ | |
$this->data = $data; | |
} | |
} | |
class NodeList { | |
private $firstNode = null; | |
private $count = 0; | |
public function insert(string $data = null){ | |
$newNode = new Node($data); | |
if($this->firstNode === null){ | |
$this->firstNode = $newNode; | |
}else{ | |
$current = $this->firstNode; | |
while($current->next !== null) { | |
$current = $current->next; | |
} | |
$current->next = $newNode; | |
} | |
$this->count++; | |
} | |
public function display(){ | |
echo "Total nodes : " . $this->count . "\n"; | |
$current = $this->firstNode; | |
while($current !== null){ | |
echo $current->data . "\n"; | |
$current = $current->next; | |
} | |
} | |
public function reverse() { | |
if ($this->firstNode !== null && $this->firstNode->next) { | |
$currentNode = $this->firstNode; | |
$reversedList = null; | |
$next = null; | |
while ($currentNode !== null) { | |
$next = $currentNode->next; | |
$currentNode->next = $reversedList; | |
$reversedList = $currentNode; | |
$currentNode = $next; | |
} | |
$this->firstNode = $reversedList; | |
} | |
} | |
} | |
$nodeList = new NodeList(); | |
// insert 3 nodes 6 , 2 , 3 | |
$nodeList->insert(6); | |
$nodeList->insert(2); | |
$nodeList->insert(3); | |
// display list's nodes | |
$nodeList->display(); | |
// reverse | |
$nodeList->reverse(); | |
// check if reversed | |
$nodeList->display(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment