Skip to content

Instantly share code, notes, and snippets.

@irfanbaigse
Created October 22, 2019 19:54
Show Gist options
  • Save irfanbaigse/14fcc35595f967ba649f29ba8b3330e0 to your computer and use it in GitHub Desktop.
Save irfanbaigse/14fcc35595f967ba649f29ba8b3330e0 to your computer and use it in GitHub Desktop.
Singly Linked List
<?php
use DataStructures\LinkedList;
$linkedList = new LinkedList();
$linkedList->inserFirst(10);
$linkedList->inserFirst(20);
$linkedList->insertLast(40);
$linkedList->insertLast(30);
<?php
namespace DataStructures;
class Node
{
public $value = null;
public $next = null;
public function __construct($data)
{
$this->value = $data;
}
public function readNode()
{
return $this->value;
}
}
{
"firstNode": {
"value": 20,
"next": {
"value": 10,
"next": {
"value": 40,
"next": {
"value": 30,
"next": null
}
}
}
},
"lastNode": {
"value": 30,
"next": null
},
"count": 4
}
<?php
namespace DataStructures;
use DataStructures\Node;
class LinkedList
{
/**
* make as public to print in json
*/
public $firstNode = null;
public $lastNode = null;
public $count = 0;
public function inserFirst($data)
{
if ($this->firstNode !== null) {
$node = $this->getNewNode($data);
$node->next = $this->firstNode;
$this->firstNode = &$node;
$this->count++;
} else {
$this->insertFirstNode($data);
}
}
public function insertLast($data)
{
if ($this->firstNode !== null) {
$node = $this->getNewNode($data);
$this->lastNode->next = $node;
$this->lastNode = &$node;
$this->count++;
} else {
$this->insertFirstNode($data);
}
}
private function insertFirstNode($data)
{
$node = $this->getNewNode($data);
$this->firstNode = &$node;
$this->lastNode = &$node;
$this->count++;
}
public function getCount()
{
return $this->count;
}
private function getNewNode($data)
{
return new Node($data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment