Linked list from user input php - php

public $head = null;
public $size = 0;
function push($value, $pos)
{
if($pos>0 && $pos>$this->size)
{
return false;
}
else{
$node = new Node($value);
if ( $pos == 0) {
$node->next=$this->head;
$this->head= $node;
$this->size++;
} else {
$current = $this->head;
for ($i = 0; $i < $pos; $i++) {
$previous = $current;
$current = $current->next;
}
$node->next = $current;
$previous->next = $node;
$this->size++;
}
}
}
function pop($pos)
{
$current=$this->head;
if($pos==0)
{
$this->head=$current->next;
}
else{
for($i=0;$i<$pos;$i++)
{
$previous=$current;
$current=$current->next;
}
$previous->next=$current->next;
}
$this->size--;
}
pushing value is working fine, but poping is not working,excuting pop() method and deleting value from database at the same time.stuck please help.
deleting value from database is easy but the order of linked list get unsorted and push method does not work.
deleting value of pos=0 will delete pos=0 from database and pos will start from pos=1 and push method is not excuting.

Related

Error when printing how many levels are visible in tree in PHP

I am receiving the error "Using $this when not in object context". I think I might be using the class node incorrectly. I cannot figure out where I am going wrong at this point.
I am trying to get the answer 4 in the case of a tree like the below. This is because there are 4 visible layers.
$root = new TreeNode(8);
$root->left = new TreeNode(3);
$root->right = new TreeNode(10);
$root->left->left = new TreeNode(1);
$root->left->right = new TreeNode(6);
$root->left->right->left = new TreeNode(4);
$root->left->right->right = new TreeNode(7);
$root->right->right = new TreeNode(14);
$root->right->right->left = new TreeNode(13);
class TreeNode{
public $val;
public $left;
public $right;
public function __construct($val=0) {
$this->val = $val;
$this->left = NULL;
$this->right = NULL;
}
}
function findLeft($root){
$queue = $root;
while(!empty($queue)){
$size = sizeof($queue);
$i = 0;
$answer = 0;
while($i<$size){
$i= $i+1;
//if first node print
if ($i == 1){
$answer += 1;
}
if($this->left){
array_push($queue, $this->left);
}
if($this->right){
array_push($queue, $this->right);
}
array_unshift($queue); //shift first item
}
} return $queue;
}
//calling function
function visibleNodes($root) {
// Write your code here
if(empty($root)){
return 0;
} else {
$answer = findLeft($root);
}
return $answer;
}

base64 in PHP Otp Library

I trying to make some simple library for encrypting files in PHP with OTP method. My problem is that some chars in decrypted code are different than original. I worked on it almost one week but without result. Is there problem with base64 chars or with encoding/decoding mechanism ?
Many thanks for the answers.
final class Otp
{
private static $charSet = array('+','/','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z');
public static function encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath)
{
if(!self::existsFile($keyFilePath) || !self::existsFile($encryptedFilePath)) {
if($originalFileData = self::existsFile($originalFilePath)) {
$originalFileBase64Data = base64_encode($originalFileData);
$originalFileBase64DataLength = strlen($originalFileBase64Data) - 1;
$originalFileBase64DataArray = str_split($originalFileBase64Data);
$encryptedData = NULL;
$encryptedDataKey = NULL;
for ($i = 0; $i <= $originalFileBase64DataLength; $i++) {
$randKey = rand(0, sizeOf(self::$charSet) - 1);
$arrayKey = array_search($originalFileBase64DataArray[$i], self::$charSet);
if($randKey > $arrayKey) {
$str = '-' . ($randKey - $arrayKey);
} elseif($randKey < $arrayKey) {
$str = ($randKey + $arrayKey);
} else {
$str = $randKey;
}
$encryptedData .= self::$charSet[$randKey];
$encryptedDataKey .= $str. ';';
}
$encryptedDataString = $encryptedData;
$encryptedDataKeyString = $encryptedDataKey;
if(!self::existsFile($keyFilePath)) {
file_put_contents($keyFilePath, $encryptedDataKeyString);
}
if(!self::existsFile($encryptedFilePath)) {
file_put_contents($encryptedFilePath, $encryptedDataString);
}
return 'OK';
} else {
return 'Source file not exists';
}
} else {
return 'Encrypted data already exists';
}
}
public static function decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath)
{
$keyFileData = self::existsFile($keyFilePath);
$encryptedFileData = self::existsFile($encryptedFilePath);
$encryptedFileDataLength = strlen($encryptedFileData) - 1;
if($encryptedFileData && $keyFileData) {
$encryptedFileDataArray = str_split($encryptedFileData);
$keyFileDataArray = explode(';', $keyFileData);
$decryptedData = NULL;
for ($i = 0; $i <= $encryptedFileDataLength; $i++) {
$poziciaaktualneho = array_search($encryptedFileDataArray[$i], self::$charSet);
$poziciasifrovana = $keyFileDataArray[$i];
if($poziciasifrovana < 0) {
$move = $poziciasifrovana + $poziciaaktualneho;
} elseif($poziciasifrovana > 0) {
$move = $poziciasifrovana - $poziciaaktualneho;
} else {
$move = '0';
}
$decryptedData .= self::$charSet[$move];
}
if(!self::existsFile($decryptedFilePath)) {
file_put_contents($decryptedFilePath, base64_decode($decryptedData));
return 'OK';
} else {
return 'Decrypted data already exists';
}
}
}
private static function existsFile($filePath)
{
$fileData = #file_get_contents($filePath);
if($fileData) {
return $fileData;
}
return FALSE;
}
}
$originalFilePath = 'original.jpg';
$keyFilePath = 'Otp_Key_' . $originalFilePath;
$encryptedFilePath = 'Otp_Data_' . $originalFilePath;
$decryptedFilePath = 'Otp_Decrypted_' . $originalFilePath;
echo Otp::encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath);
echo Otp::decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath);
The problem seems to be only happening when $poziciaaktualneho is equal to $poziciasifrovana and so by adding another if statement on line 78 to check for this and instead set $move equal to $poziciasifrovana I was able to fix the problem. The below script should work:
final class Otp
{
private static $charSet = array('+','/','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z');
public static function encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath)
{
if(!self::existsFile($keyFilePath) || !self::existsFile($encryptedFilePath)) {
if($originalFileData = self::existsFile($originalFilePath)) {
$originalFileBase64Data = base64_encode($originalFileData);
$originalFileBase64DataLength = strlen($originalFileBase64Data) - 1;
$originalFileBase64DataArray = str_split($originalFileBase64Data);
$encryptedData = NULL;
$encryptedDataKey = NULL;
for ($i = 0; $i <= $originalFileBase64DataLength; $i++) {
$randKey = rand(0, sizeOf(self::$charSet) - 1);
$arrayKey = array_search($originalFileBase64DataArray[$i], self::$charSet);
if($randKey > $arrayKey) {
$str = '-' . ($randKey - $arrayKey);
} elseif($randKey < $arrayKey) {
$str = ($randKey + $arrayKey);
} else {
$str = $randKey;
}
$encryptedData .= self::$charSet[$randKey];
$encryptedDataKey .= $str. ';';
}
$encryptedDataString = $encryptedData;
$encryptedDataKeyString = $encryptedDataKey;
if(!self::existsFile($keyFilePath)) {
file_put_contents($keyFilePath, $encryptedDataKeyString);
}
if(!self::existsFile($encryptedFilePath)) {
file_put_contents($encryptedFilePath, $encryptedDataString);
}
return 'OK';
} else {
return 'Source file not exists';
}
} else {
return 'Encrypted data already exists';
}
}
public static function decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath)
{
$keyFileData = self::existsFile($keyFilePath);
$encryptedFileData = self::existsFile($encryptedFilePath);
$encryptedFileDataLength = strlen($encryptedFileData) - 1;
if($encryptedFileData && $keyFileData) {
$encryptedFileDataArray = str_split($encryptedFileData);
$keyFileDataArray = explode(';', $keyFileData);
$decryptedData = NULL;
for ($i = 0; $i <= $encryptedFileDataLength; $i++) {
$poziciaaktualneho = array_search($encryptedFileDataArray[$i], self::$charSet);
$poziciasifrovana = $keyFileDataArray[$i];
if ($poziciasifrovana == $poziciaaktualneho) {
$move = $poziciasifrovana;
} elseif($poziciasifrovana < 0) {
$move = $poziciasifrovana + $poziciaaktualneho;
} elseif($poziciasifrovana > 0) {
$move = $poziciasifrovana - $poziciaaktualneho;
} else {
$move = '0';
}
$decryptedData .= self::$charSet[$move];
}
if(!self::existsFile($decryptedFilePath)) {
file_put_contents($decryptedFilePath, base64_decode($decryptedData));
return 'OK';
} else {
return 'Decrypted data already exists';
}
}
}
private static function existsFile($filePath)
{
$fileData = #file_get_contents($filePath);
if($fileData) {
return $fileData;
}
return FALSE;
}
}
$originalFilePath = 'original.jpg';
$keyFilePath = 'Otp_Key_' . $originalFilePath;
$encryptedFilePath = 'Otp_Data_' . $originalFilePath;
$decryptedFilePath = 'Otp_Decrypted_' . $originalFilePath;
echo Otp::encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath);
echo Otp::decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath);
Warning: I would not recommend using my solution in an enterprise setting if at all since I do not know why this fixes your script or what was
originally wrong with it and it is most likely not air tight.

gallery with next and prev function

I'm working on an image gallery as my first real project as of learning php.. The problem I'm not able to get around somehow is using the "previous" button. My "next" function grabs the next 6 images from the folder and posts them to the page, my prev function does this in reverse.. but that's incorrect, can you help? oh, and this code is sloppy beginner code so i'm happy for tips :)
<?php
session_start();
if(session_id() == '') {
$_SESSION["count"] = 0;
}
function PostHTML($id, $file) {
if($id==0) {
echo "<div class=\"item\"><div class=\"well\"><img
class=\"img-responsive\" src=\"$file\" alt=\"\"><p>blahblahblah xxxxxx</p></div></div>";
}else{
echo "<div class=\"item\"><div class=\"well\"><video autoplay
loop class=\"img-responsive\"><source src=\"$file\" type=\"video/mp4\"></video></div></div>";
}
}
function next_img() {
$dir = "images/src/*.*";
$files = array();
$start = $_SESSION["count"];
$end = $_SESSION["count"]+6;
$y=0;
foreach(glob($dir) as $file) {
$files[$y] = $file;
$y++;
}
for($i=$start; $i < $end; $i++){
if(pathinfo($files[$i], PATHINFO_EXTENSION)=="jpg") {
PostHTML(0,$files[$i]);
} else {
PostHTML(1,$files[$i]); }
}
$_SESSION["count"]+=6;
}
function prev_img() {
$dir = "images/src/*.*";
$files = array();
$start = $_SESSION["count"]-1;
$end = $_SESSION["count"]-6;
$y=0;
foreach(glob($dir) as $file) {
$files[$y] = $file; //100 files
$y++;
}
for ($i = $start; $i > $end; $i--) {
if(pathinfo($files[$i], PATHINFO_EXTENSION)=="jpg") {
PostHTML(0,$files[$i]);
} else {
PostHTML(1,$files[$i]);
}
}
$_SESSION["count"]-=6;
}
?>
If i were to do something like this I might create a File Controller class to manage all the file operations i might need.
<?php
class FileController
{
private $_dir = "DIR";
private $files;
private $current;
function__construct()
{
$current = 0;
$files = scandir($_dir); // scans the dir to get a list of file names
if(!$files) echo "Failed To Load Files"; // failed to load files
else
{
$this->file = $files; // objects propery contains all file names in array;
}
}
function PostHTML($fileName) {
$src = $this->_dir + "/" + $fileName;
if(!$fileName)
{
return "<div class=\"item\"><div class=\"well\"><img
class=\"img-responsive\" src=\"$src\" alt=\"\"><p>blahblahblah xxxxxx</p></div></div>";
}
else
{
return "<div class=\"item\"><div class=\"well\"><video autoplay
loop class=\"img-responsive\"><source src=\"$src\" type=\"video/mp4\"></video></div></div>";
}
}
function nextImg()
{
$current = $this->getCurrent();
$end = $current + 6;
$this->setCurrent($end);
$files = $this->files;
$html = "";
for($i = $current; $i<= $end; $i++)
{
$html += postHtml($files[$i]);
}
echo $html;
}
function prevImg()
{
$current = $this->getCurrent();
$end = $current - 6;
$this->setCurrent($end);
$files = $this->files;
$html = "";
for($i = $current; $i>= $end; $i--)
{
$html += postHtml($files[$i]);
}
echo $html;
}
function getCurrent()
{
return $_SESSION['current'];
}
function setCurrent($current)
{
$_SESSION['current'] = $current;
}
}
?>

PHP recursive function nesting level reached

Good day. I have a parcer function that taker an array of string like this:
['str','str2','str2','*str','*str2','**str2','str','str2','str2']
And recursivelly elevates a level those starting with asterix to get this
['str','str2','str2',['str','str2',['str2']],'str','str2','str2']
And the function is:
function recursive_array_parser($ARRAY) {
do {
$i = 0;
$s = null;
$e = null;
$err = false;
foreach ($ARRAY as $item) {
if (!is_array($item)) { //if element is not array
$item = trim($item);
if ($item[0] === '*' && $s == null && $e == null) { //we get it's start and end if it has asterix
$s = $i;
$e = $i;
} elseif ($item[0] === '*' && $e != null)
$e = $i;
elseif (!isset($ARRAY[$i + 1]) || $s != null && $e != null) { //if there are no elements or asterix element ended we elevate it
$e = $e == NULL ? $i : $e;
$head = array_slice($ARRAY, 0, $s);
$_x = [];
$inner = array_slice($ARRAY, $s, $e - $s + 1);
foreach ($inner as $_i)
$_x[] = substr($_i, 1);
$inner = [$_x];
$tail = array_slice($ARRAY, $e + 1, 999) or [];
$X = array_merge($head, $inner);
$ARRAY = array_merge($X, $tail);
$s = null;
$e = null;
$err = true;
}
} else {
$ARRAY[$i] = recursive_array_parser($ARRAY[$i]); //if the item is array of items we recur.
}
$i++;
if ($err == true) {
break 1;
}
}
} while ($err);
return $ARRAY;
}
When this function runs, i get "Fatal error: Maximum function nesting level of '200' reached, aborting!" error.
I know it has something to do with infinite recursion, but i can't track the particular place where it occurs, and this is strange.
I don't normally rewrite code, but your code can be reduced and simplified while, from what I can see, getting the desired result. See if this works for you:
$a = array('a','b','c','*d','*e','**f','g','*h');
print_r($a);
$a = recursive_array_parser($a);
print_r($a);
function recursive_array_parser($array)
{
$ret = array();
for($i=0; $i<sizeof($array); $i++)
{
if($array[$i]{0}!='*') $ret[] = $array[$i];
else
{
$tmp = array();
for($j=$i; $j<sizeof($array) && $array[$j]{0}=='*'; $j++)
{
$tmp[] = substr($array[$j],1);
}
$ret[] = recursive_array_parser($tmp);
$i = $j-1;
}
}
return $ret;
}
Note that it isn't possible for $array[$i] to be an array, so that check is removed. The recursion takes place on the temp array created when a * is found. The $i is closer tied to $array to reset it properly after parsing the series of * elements.
Here's my solution. No nested loops.
function recursive_array_parser($arr) {
$out = array();
$sub = null;
foreach($arr as $item) {
if($item[0] == '*') { // We've hit a special item!
if(!is_array($sub)) { // We're not currently accumulating a sub-array, let's make one!
$sub = array();
}
$sub[] = substr($item, 1); // Add it to the sub-array without the '*'
} else {
if(is_array($sub)) {
// Whoops, we have an active subarray, but this thing didn't start with '*'. End that sub-array
$out[] = recursive_array_parser($sub);
$sub = null;
}
// Take the item
$out[] = $item;
}
}
if(is_array($sub)) { // We ended in an active sub-array. Add it.
$out[] = recursive_array_parser($sub);
$sub = null;
}
return $out;
}

Implement linked list in php

How should I implement a linked list in PHP? Is there a implementation built in into PHP?
I need to do a lot of insert and delete operations, and at same time I need to preserve order.
I'd like to use only PHP without any special extensions.
There is SplDoublyLinkedList. Is this okay, too?
Here is a linked list implementation in PHP pulled from: http://www.codediesel.com/php/linked-list-in-php/ which can add, delete, reverse and empty a linkedlist in PHP.
<?php
class ListNode
{
public $data;
public $next;
function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
function readNode()
{
return $this->data;
}
}
class LinkList
{
private $firstNode;
private $lastNode;
private $count;
function __construct()
{
$this->firstNode = NULL;
$this->lastNode = NULL;
$this->count = 0;
}
//insertion at the start of linklist
public function insertFirst($data)
{
$link = new ListNode($data);
$link->next = $this->firstNode;
$this->firstNode = &$link;
/* If this is the first node inserted in the list
then set the lastNode pointer to it.
*/
if($this->lastNode == NULL)
$this->lastNode = &$link;
$this->count++;
}
//displaying all nodes of linklist
public function readList()
{
$listData = array();
$current = $this->firstNode;
while($current != NULL)
{
array_push($listData, $current->readNode());
$current = $current->next;
}
foreach($listData as $v){
echo $v." ";
}
}
//reversing all nodes of linklist
public 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;
}
}
}
//deleting a node from linklist $key is the value you want to delete
public function deleteNode($key)
{
$current = $this->firstNode;
$previous = $this->firstNode;
while($current->data != $key)
{
if($current->next == NULL)
return NULL;
else
{
$previous = $current;
$current = $current->next;
}
}
if($current == $this->firstNode)
{
if($this->count == 1)
{
$this->lastNode = $this->firstNode;
}
$this->firstNode = $this->firstNode->next;
}
else
{
if($this->lastNode == $current)
{
$this->lastNode = $previous;
}
$previous->next = $current->next;
}
$this->count--;
}
//empty linklist
public function emptyList()
{
$this->firstNode == NULL;
}
//insertion at index
public function insert($NewItem,$key){
if($key == 0){
$this->insertFirst($NewItem);
}
else{
$link = new ListNode($NewItem);
$current = $this->firstNode;
$previous = $this->firstNode;
for($i=0;$i<$key;$i++)
{
$previous = $current;
$current = $current->next;
}
$previous->next = $link;
$link->next = $current;
$this->count++;
}
}
}
$obj = new LinkList();
$obj->insertFirst($value);
$obj->insert($value,$key); // at any index
$obj->deleteNode($value);
$obj->readList();
Here is the code in php which will implement Linked List, only with the reference of head node i.e first node and then you add at first, last and delete a key, and also maintain the code of the keys in list.
<?php
/**
* Class Node
*/
class Node
{
public $data;
public $next;
public function __construct($item)
{
$this->data = $item;
$this->next = null;
}
}
/**
* Class LinkList
*/
class LinkList
{
public $head = null;
private static $count = 0;
/**
* #return int
*/
public function GetCount()
{
return self::$count;
}
/**
* #param mixed $item
*/
public function InsertAtFist($item) {
if ($this->head == null) {
$this->head = new Node($item);
} else {
$temp = new Node($item);
$temp->next = $this->head;
$this->head = $temp;
}
self::$count++;
}
/**
* #param mixed $item
*/
public function InsertAtLast($item) {
if ($this->head == null) {
$this->head = new Node($item);
} else {
/** #var Node $current */
$current = $this->head;
while ($current->next != null)
{
$current = $current->next;
}
$current->next = new Node($item);
}
self::$count++;
}
/**
* Delete the node which value matched with provided key
* #param $key
*/
public function Delete($key)
{
/** #var Node $current */
$current = $previous = $this->head;
while($current->data != $key) {
$previous = $current;
$current = $current->next;
}
// For the first node
if ($current == $previous) {
$this->head = $current->next;
}
$previous->next = $current->next;
self::$count--;
}
/**
* Print the link list as string like 1->3-> ...
*/
public function PrintAsList()
{
$items = [];
/** #var Node $current */
$current = $this->head;
while($current != null) {
array_push($items, $current->data);
$current = $current->next;
}
$str = '';
foreach($items as $item)
{
$str .= $item . '->';
}
echo $str;
echo PHP_EOL;
}
}
$ll = new LinkList();
$ll->InsertAtLast('KP');
$ll->InsertAtLast(45);
$ll->InsertAtFist(11);
$ll->InsertAtLast('FE');
$ll->InsertAtFist('LE');
$ll->InsertAtFist(100);
$ll->InsertAtFist(199);
$ll->InsertAtLast(500);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
$ll->Delete(45);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
$ll->Delete(500);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
$ll->Delete(100);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
Code out put as:
$ php LinkList.php
199->100->LE->11->KP->45->FE->500->
Total elements 8
199->100->LE->11->KP->FE->500->
Total elements 7
199->100->LE->11->KP->FE->
Total elements 6
199->LE->11->KP->FE->
Total elements 5
Here is another Linked list implementation using an array of elements. The add function keeps the elements sorted.
<?php
class LinkedList{
private $_head = null;
private $_list = array();
public function addNode($val) {
// add the first element
if(empty($this->_list)) {
$this->_head = $val;
$this->_list[$val] = null;
return;
}
$curr = $this->_head;
while ($curr != null || $curr === 0) {
// end of the list
if($this->_list[$curr] == null) {
$this->_list[$curr] = $val;
$this->_list[$val] = null;
return;
}
if($this->_list[$curr] < $val) {
$curr = $this->_list[$curr];
continue;
}
$this->_list[$val] = $this->_list[$curr];
$this->_list[$curr] = $val;
return;
}
}
public function deleteNode($val) {
if(empty($this->_list)) {
return;
}
$curr = $this->_head;
if($curr == $val) {
$this->_head = $this->_list[$curr];
unset($this->_list[$curr]);
return;
}
while($curr != null || $curr === 0) {
// end of the list
if($this->_list[$curr] == null) {
return;
}
if($this->_list[$curr] == $val) {
$this->_list[$curr] = $this->_list[$val];
unset($this->_list[$val]);
return;
}
$curr = $this->_list[$curr];
}
}
function showList(){
$curr = $this->_head;
while ($curr != null || $curr === 0) {
echo "-" . $curr;
$curr = $this->_list[$curr];
}
}
}
$list = new LinkedList();
$list->addNode(0);
$list->addNode(3);
$list->addNode(7);
$list->addNode(5);
$list->addNode(2);
$list->addNode(4);
$list->addNode(10);
$list->showList();
echo PHP_EOL;
$list->deleteNode(3);
$list->showList();
echo PHP_EOL;
$list->deleteNode(0);
$list->showList();
echo PHP_EOL;
The output is:
-0-2-3-4-5-7-10
-0-2-4-5-7-10
-2-4-5-7-10
I was also trying to write a program to create a linked list in PHP. Here is what I have written and it worked for me. I hope it helps to answer the question.
Created a php file. Name: LinkedList.php
{code}
<?php
require_once (__DIR__ . "/LinkedListNodeClass.php");
$node_1 = new Node();
Node::createNode($node_1, 5);
echo "\n Node 1 is created.";
$head = &$node_1;
echo "\n Head is intialized with Node 1.";
$node_2 = new Node();
Node::createNode($node_2, 1);
echo "\n Node 2 is created.";
Node::insertNodeInLinkedList($head, $node_2);
$node_3 = new Node();
Node::createNode($node_3, 11);
echo "\n Node 3 is created.";
Node::insertNodeInLinkedList($head, $node_3);
$node_4 = new Node();
Node::createNode($node_4, 51);
echo "\n Node 4 is created.";
Node::insertNodeInLinkedList($head, $node_4);
$node_5 = new Node();
Node::createNode($node_5, 78);
echo "\n Node 5 is created.";
Node::insertNodeInLinkedList($head, $node_5);
$node_6 = new Node();
Node::createNode($node_6, 34);
echo "\n Node 6 is created.";
Node::insertNodeInLinkedList($head, $node_6);
$node_7 = new Node();
Node::createNode($node_7, 99);
echo "\n Node 7 is created.";
Node::insertNodeInHeadOfLinkedList($head, $node_7);
$node_8 = new Node();
Node::createNode($node_8, 67);
echo "\n Node 8 is created.";
Node::insertNodeInHeadOfLinkedList($head, $node_8);
$node_9 = new Node();
Node::createNode($node_9, 101);
echo "\n Node 9 is created.";
Node::insertNodeAfterAPositionInLinkedList($head, 5, $node_9);
$node_10 = new Node();
Node::createNode($node_10, 25);
echo "\n Node 10 is created.";
Node::insertNodeAfterAPositionInLinkedList($head, 2, $node_10);
echo "\n Displaying the linked list: \n";
Node::displayLinkedList($head);
?>
{code}
This file is calling a class to create, insert and display nodes in linked list. Name: LinkedListNodeClass.php
{code}
<?php
class Node {
private $data;
private $next;
public function __construct() {
//does nothing...
}
//Creates a node
public function createNode($obj, $value) {
$obj->data = $value;
$obj->next = NULL;
}
//Inserts a created node in the end of a linked list
public function insertNodeInLinkedList($head, &$newNode) {
$node = $head;
while($node->next != NULL){
$node = $node->next;
}
$node->next = $newNode;
}
//Inserts a created node in the start of a linked list
public function insertNodeInHeadOfLinkedList(&$head, &$newNode) {
$top = $head;
$newNode->next = $top;
$head = $newNode;
}
//Inserts a created node after a position of a linked list
public function insertNodeAfterAPositionInLinkedList($head, $position, &$newNode) {
$node = $head;
$counter = 1;
while ($counter < $position){
$node = $node->next;
$counter++;
}
$newNode->next = $node->next;
$node->next = $newNode;
}
//Displays the Linked List
public function displayLinkedList($head) {
$node = $head;
print($node->data); echo "\t";
while($node->next != NULL){
$node = $node->next;
print($node->data); echo "\t";
}
}
}
?>
{code}
If don't think most people understand what linked lists are. The basic idea is you want to keep data organised is such a way that you can access the previous and next node using the current node. The other features like add, delete, insert, head etc are sugar, though necessary. I think the SPL package does cover a lot. Problem is I need a PHP 5.2.9 class. Guess I've to implement it myself.
Just to clarify, implementing linked list in PHP using PHP arrays probably is not a good idea, because PHP array is hash-table under the hood (not simple low-level arrays). Simultaneously, you don't get advantages of pointers.
Instead, you can implement data structures like linked list for PHP using extensions, that means you are implementing a data structure in C to PHP.
Spl data structures are an example, another example is php-ds extension, specially in case of linked lists, you can use this: https://www.php.net/manual/en/class.ds-sequence.php
Sequence ADT is the unification of List ADT and Vector ADT, so you can use Sequence ADT implemented data structures as lists.
Hope this could help someone choose wisely.
// Here's a basic implementation of SplDoublyLinkedList using PHP.
$splDoubleLinkedList = new SplDoublyLinkedList();
$splDoubleLinkedList->push('a');
$splDoubleLinkedList->push('3');
$splDoubleLinkedList->push('v');
$splDoubleLinkedList->push('1');
$splDoubleLinkedList->push('p');
// $splDoubleLinkedList->unshift('10');
// $splDoubleLinkedList->pop();
$splDoubleLinkedList->add(3, 3.0);
// First of all, we need to rewind list.
$splDoubleLinkedList->rewind();
// Use while, check if the list has valid node.
while($splDoubleLinkedList->valid()){
// Print current node's value.
echo $splDoubleLinkedList->current()."\n";
// Turn the cursor to next node.
$splDoubleLinkedList->next();
}

Categories