Consider the following linked list
a->b->c->c->b->a->null is palindrome .
there are two ways to find out whether the given linked list is a palindrome or not
1. Use stack . push the first half of the linked list into stack and pop elements from stack & check it with the second half .But it needs extra space.
2. Reverse the second half of the linked list .so it will become a->b->c->a->b->c->null .Compare the first half with the second half . Here u need to find the length of the linked list and reverse of linked list .Its already posted in this site. That's of the beauty of writing functions . U can reuse it whenever u want . Refer it here if u want
i) Length of the linked list
ii) Code to reverse the linked list .
Code: (in C)
int check_palindrome(struct node* head)
{
int length=size_of_linkedlist(head),middle;
if(length < 2)
return 1;
struct node* first_half=head,second_half=head,reversed_second_half,temp;
// find the middle element and move the second_half pointer to second half
if(length%2==0)
middle=length/2+1;
else
middle=length/2+2;
while(--middle!=0)
second_half=second_half->link;
//reverse the second half of the linked list
temp=reversed_second_half=reverse(second_half);
//compare first half and second half
while(temp!=null)
{
if(temp->data != first_half->data)
{
second_half=reverse(reversed_second_half);
return 0;
}
temp=temp->link;
}
//reverse again the second half so that original list wont be changed .
second_half=reverse(reversed_second_half);
return 1;
}
Please let me know if there is any bug in the above code and your suggestions are always welcome .
No comments:
Post a Comment