C++ program for detect palindrome in doubly linked list
C++ program for Detect palindrome in doubly linked list. Here more information.
// Include header file
#include <iostream>
using namespace std;
// C++ program for
// Check if palindrome exists in doubly linked list
// This is Linked List Node
class LinkNode
{
public: int data;
LinkNode *next;
LinkNode *prev;
LinkNode(int data)
{
this->data = data;
this->next = nullptr;
this->prev = nullptr;
}
};
class DoublyLinkedList
{
public: LinkNode *head;
LinkNode *tail;
DoublyLinkedList()
{
this->head = nullptr;
this->tail = nullptr;
}
// Insert new node at end position
void insert(int value)
{
// Create a node
LinkNode *node = new LinkNode(value);
if (this->head == nullptr)
{
// 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
void display()
{
if (this->head == nullptr)
{
cout << "Empty Linked List" << endl;
}
else
{
cout << "Linked List Head to Tail :";
// Get first node of linked list
LinkNode *temp = this->head;
// iterate linked list
while (temp != nullptr)
{
// Display node value
cout << " " << temp->data;
// Visit to next node
temp = temp->next;
}
cout << "\nLinked List Tail to Head :";
// Get last node of linked list
temp = this->tail;
// iterate linked list
while (temp != nullptr)
{
// Display node value
cout << " " << temp->data;
// Visit to prev node
temp = temp->prev;
}
}
}
bool isPalindrome()
{
if (this->head == nullptr)
{
// When empty linked list
return false;
}
LinkNode *first = this->head;
LinkNode *last = this->tail;
while (last != nullptr &&
first != nullptr &&
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;
}
};
int main()
{
DoublyLinkedList *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)
{
cout << "\nYes" << endl;
}
else
{
cout << "\nNo" << endl;
}
// Add new element
dll->insert(1);
dll->display();
// Test B
if (dll->isPalindrome() == true)
{
cout << "\nYes" << endl;
}
else
{
cout << "\nNo" << endl;
}
return 0;
}
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