Friday, 12 August 2016

Check if Linked List is a Palindrome in O(n)

#include <iostream>
using namespace std;
struct node {
char data; //can be integer
node * next;
};

void palindrome(node * head)
{

node * p= head;
node *p1=head;
if(head==NULL)
return ;

//Finding middle element
while(p1!=NULL && p1->next!=NULL)
{

p1=p1->next->next;
p=p->next;
}
//Reversing list from middle element
node *curr=p;
node *prev=NULL;
node *next;
while(curr!=NULL)
{
next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
}
p=prev;

//Comparing two halves of Linked List
node *u=p;
node *t=head;
int f=0;
while(u!=NULL)
{

if(u->data!=t->data)
{
f=1;
break;
}
u=u->next;
t=t->next;
}

if(f==1)
cout<<"No\n";
else
cout<<"Yes\n";
}

int main() {
node *start,*p,*p1,*p2,*p3,*p4;
start=new node;
p=new node ;
p1=new node ;
p2=new node ;
p3=new node ;
p4=new node ;
start->data='a';
p->data='b';
p1->data='c';
p2->data='c';
p3->data='b';
p4->data='a';
start->next=p;
p->next=p1;
p1->next=p2;
p2->next=p3;
p3->next=p4;
p4->next=NULL;
palindrome(start);

return 0;
}

No comments:

Post a Comment