Wednesday, February 23, 2011

Java program to check if a Linked List is a palindrome


Algorithm:
1. Find the length of the list.
2. Reverse the list from the middle.
3.Compare the lists
4.Reverse the second half again and join back.

Java Program:

public boolean isPalindrome()
{
int len=getLength(); //gets the length of the list
int mid=(len/2)+1;
ListNode temp=headnode;
int i=1;
while(i<mid)
{
temp=temp.nextnode;
i++;
}

ListNode newlisthead=temp.nextnode;
ListNode middlenode=temp;

ListNode temp1,temp2,temp3;

temp1=newlisthead;
temp2=newlisthead.nextnode;
temp3=null;
newlisthead.nextnode=null;
while(temp2.nextnode!=null)
{
temp3=temp2.nextnode;
temp2.nextnode=temp1;
temp1=temp2;
temp2=temp3;
}
temp2.nextnode=temp1;
newlisthead=temp2;
ListNode lastnode=newlisthead;  
// Start comparison

temp1=headnode;
temp2=newlisthead;

boolean palindrome=true;

while(temp2!=null)
{
Comparable dat1=(Comparable)temp1.data;
if(dat1.compareTo(temp2.data)!=0)
{
temp1=newlisthead;
temp2=newlisthead.nextnode;
temp3=null;
newlisthead.nextnode=null;
while(temp2.nextnode!=null)
{
temp3=temp2.nextnode;
temp2.nextnode=temp1;
temp1=temp2;
temp2=temp3;
}
temp2.nextnode=temp1;

newlisthead=temp2;
middlenode.nextnode=newlisthead;
lastnode.nextnode=null;
return false;
}

else
{
temp1=temp1.nextnode;
temp2=temp2.nextnode;
}
}

temp1=newlisthead;
temp2=newlisthead.nextnode;
temp3=null;
newlisthead.nextnode=null;
while(temp2.nextnode!=null)
{
temp3=temp2.nextnode;
temp2.nextnode=temp1;
temp1=temp2;
temp2=temp3;
}
temp2.nextnode=temp1;

newlisthead=temp2;
middlenode.nextnode=newlisthead;
lastnode.nextnode=null;
return true;


}

No comments: