Skip to content

Instantly share code, notes, and snippets.

@antoniopicone
Last active April 25, 2023 22:46
Show Gist options
  • Save antoniopicone/cddf68ef141ac2cf1b3095e22babf969 to your computer and use it in GitHub Desktop.
Save antoniopicone/cddf68ef141ac2cf1b3095e22babf969 to your computer and use it in GitHub Desktop.
A simple Linked List in PHP
<?php
class Node {
public $data;
public $next;
public function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
public function getData()
{
return $this->data;
}
}
class LinkedList { // REMEMBER, it's NOT a queue: each node is inserted as firstNode
private $firstNode;
private $lastNode;
public function __construct()
{
$this->firstNode = $this->lastNode = NULL;
}
public function isEmpty() {
return $this->firstNode == NULL;
}
public function emptyList() {
$this->__construct();
}
public function insertNode($data) {
$new_node = new Node($data);
$new_node->next = &$this->firstNode;
$this->firstNode = &$new_node;
if($this->lastNode == NULL) $this->lastNode = &$new_node;
}
public function deleteNode($data) {
$current = $previous = $this->firstNode;
while ($current != NULL) {
if($current->getData() == $data) {
$previous->next = $current->next;
if($current == $this->firstNode) $this->firstNode = $current->next;
if($current == $this->lastNode) $this->lastNode = $previous;
}
$previous = $current;
$current = $current->next;
}
}
public function traverseList() {
$current_node = $this->firstNode;
while($current_node != NULL) {
echo $current_node->getData().'->';
$current_node = $current_node->next;
}
echo "NULL\n";
}
function reverseList() {
if($this->firstNode != NULL) {
if($this->firstNode->next != NULL) {
$current = $this->firstNode;
$new = NULL;
while($current != NULL) {
$temp = $current->next;
$current->next = $new;
$new = $current;
$current = $temp;
}
$this->firstNode = $new;
}
}
}
}
$ll = new LinkedList();
$ll->insertNode(3);
$ll->insertNode(2);
$ll->insertNode(4);
$ll->insertNode(5);
$ll->traverseList();
$ll->deleteNode(3);
$ll->traverseList();
$ll->reverseList();
$ll->traverseList();
@mohamedsst3
Copy link

there's a problem in deleteNode method please fix it
or tell me what is the solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment