Check palindrome in a doubly linked list in php
Php program for Detect palindrome in doubly linked list. Here more information.
<?php
// Php program for
// Check if palindrome exists in doubly linked list
// This is Linked List Node
class LinkNode
{
public $data;
public $next;
public $prev;
public function __construct($data)
{
$this->data = $data;
$this->next = NULL;
$this->prev = NULL;
}
}
class DoublyLinkedList
{
public $head;
public $tail;
public function __construct()
{
$this->head = NULL;
$this->tail = NULL;
}
// Insert new node at end position
public function insert($value)
{
// Create a node
$node = new LinkNode($value);
if ($this->head == NULL)
{
// Add first node
$this->head = $node;
$this->tail = $node;
return;
}
// Add node at last position
$this->tail->next = $node;
$node->prev = $this->tail;
$this->tail = $node;
}
// Display node element of doubly linked list
public function display()
{
if ($this->head == NULL)
{
echo "Empty Linked List\n";
}
else
{
echo "Linked List Head to Tail :";
// Get first node of linked list
$temp = $this->head;
// iterate linked list
while ($temp != NULL)
{
// Display node value
echo " ",$temp->data;
// Visit to next node
$temp = $temp->next;
}
echo "\nLinked List Tail to Head :";
// Get last node of linked list
$temp = $this->tail;
// iterate linked list
while ($temp != NULL)
{
// Display node value
echo " ",$temp->data;
// Visit to prev node
$temp = $temp->prev;
}
}
}
public function isPalindrome()
{
if ($this->head == NULL)
{
// When empty linked list
return false;
}
$first = $this->head;
$last = $this->tail;
while ($last != NULL &&
$first != NULL &&
$first != $last)
{
if ($first->data != $last->data)
{
// When node value are not same
return false;
}
if ($first->next == $last)
{
// When get last pair
if ($first->data == $last->data)
{
// When pair value is same
return true;
}
// When last middle node not same
return false;
}
// Visit to next node
$first = $first->next;
// Visit to previous node
$last = $last->prev;
}
return true;
}
public static
function main($args)
{
$dll = new DoublyLinkedList();
// Insert following linked list nodes
$dll->insert(1);
$dll->insert(2);
$dll->insert(4);
$dll->insert(3);
$dll->insert(4);
$dll->insert(2);
$dll->insert(1);
// Display all node
$dll->display();
// Test A
if ($dll->isPalindrome() == true)
{
echo "\nYes\n";
}
else
{
echo "\nNo\n";
}
// Add new element
$dll->insert(1);
$dll->display();
// Test B
if ($dll->isPalindrome() == true)
{
echo "\nYes\n";
}
else
{
echo "\nNo\n";
}
}
}
DoublyLinkedList::main(array());
Output
Linked List Head to Tail : 1 2 4 3 4 2 1
Linked List Tail to Head : 1 2 4 3 4 2 1
Yes
Linked List Head to Tail : 1 2 4 3 4 2 1 1
Linked List Tail to Head : 1 1 2 4 3 4 2 1
No
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