construct a linked list from 2d matrix in php
Php program for construct a linked list from 2d matrix. Here more information.
<?php
// Php program for
// Construct a linked list from 2D matrix
class LinkNode
{
public $data;
public $next;
public $down;
public function __construct($data)
{
$this->data = $data;
$this->next = NULL;
$this->down = NULL;
}
}
class DoublyLinkedList
{
public $head;
public function __construct()
{
$this->head = NULL;
}
public function display()
{
if ($this->head == NULL)
{
echo "Empty linked list";
}
else
{
$front = $this->head;
$right = NULL;
while ($front != NULL)
{
$right = $front;
while ($right != NULL)
{
echo strval($right->data).
" ";
$right = $right->next;
}
echo "\n";
// Visit to down node
$front = $front->down;
}
}
}
public function insertData($matrix, $rows, $cols)
{
// Some auxiliary variables
$levelHead = NULL;
$root = NULL;
$perv = NULL;
$i = 0;
$j = 0;
// Add first row elements into result list
while ($i < $cols)
{
if ($this->head == NULL)
{
// Add first node
$this->head = new LinkNode($matrix[0][$i]);
$levelHead = $this->head;
}
else
{
// next head
$levelHead->next = new LinkNode($matrix[0][$i]);
$levelHead = $levelHead->next;
}
$i++;
}
// Get first element
$levelHead = $this->head;
$i = 1;
// Add all the bottom element of each column
while ($i < $rows)
{
$root = NULL;
$perv = $root;
while ($j < $cols)
{
$levelHead->down = new LinkNode($matrix[$i][$j]);
if ($root == NULL)
{
$root = $levelHead->down;
$perv = $root;
}
else
{
$perv->next = $levelHead->down;
$perv = $levelHead->down;
}
$levelHead = $levelHead->next;
$j++;
}
$levelHead = $root;
// reset col
$j = 0;
// change row
$i++;
}
}
public static
function main($args)
{
$dll = new DoublyLinkedList();
// Create 2D metrix
$matrix = array(
array(1, 6, 9, 2, -9),
array(2, 5, -5, 7, 1),
array(3, 4, 1, 8, 2)
);
$rows = count($matrix);
$cols = count($matrix[0]);
$dll->insertData($matrix, $rows, $cols);
$dll->display();
}
}
DoublyLinkedList::main(array());
Output
1 6 9 2 -9
2 5 -5 7 1
3 4 1 8 2
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment