Skip to content

Instantly share code, notes, and snippets.

@dialyy
Last active March 14, 2022 16:20
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 dialyy/de21c838884fad22324cd46f51803e0b to your computer and use it in GitHub Desktop.
Save dialyy/de21c838884fad22324cd46f51803e0b to your computer and use it in GitHub Desktop.
php : reverse a linked list
<?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