Find the middle of the linked list, reverse the second half and compare it with the first half.
//https://www.geeksforgeeks.org/find-length-of-loop-in-linked-list/
#include<bits/stdc++.h>
using namespace std;
struct linked_list {
char data;
struct linked_list* next;
};
typedef struct linked_list node;
node* insert(node* head, char n) {
node* list = (node*)malloc(sizeof(node*));
list->data=n;
list->next=head;
head=list;
return head;
}
void print(node* head) {
node* n = head;
while (n != NULL) {
cout<< n->data << "->";
n = n->next;
}
}
node* reverse(node* head) {
node *prev = NULL, *current = head, *next=NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
void isPalindrome (node* head) {
node *slow=head, *fast=head;
if (head != NULL) {
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
}
if(fast == NULL) {
slow = reverse(slow);
while (slow != NULL) {
if (slow->data != head->data) {
cout<< "Not a palindrome\n";
return;
}
slow = slow->next;
head = head->next;
}
cout<< "Is a Palindrome!\n";
return;
}
if (fast->next == NULL) {
slow = reverse(slow->next);
while (slow != NULL) {
if (slow->data != head->data) {
cout<< "Not a palindrome\n";
return;
}
slow = slow->next;
head = head->next;
}
cout<< "Is a Palindrome!\n";
return;
}
}
int main() {
string s;
cout<<"enter the string: ";
cin>>s;
int n = s.length();
if (n == 1){
cout<< "String length has to be more than 2...";
exit(0);
}
node* head = NULL;
for(int i=0;i<n;i++) {
head = insert(head, s[i]);
}
print (head);
cout<< "\n";
isPalindrome(head);
}