Check if Linked List is Pallindrome

PROBLEM :

Given a singly linked list of integers, Your task is to complete a function that returns true if the given list is palindrome, else returns false.

Input:
The first line of input contains an integer T denoting the no of test cases. Then T testcases follow. Each test case contains 2 line the first line contains an integer N denoting the size of the linked list. In the next line are N space separated values of the nodes of the linked list.

Output:
For each test case output will be 1 if the linked list is a pallindrome else 0.

Constraints:
1<=T<=1000
1<=N<=50

Example(To be used only for expected output):

Input
2
3
1 2 1
4
1 2 3 4

Output:
1
0

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*The structure of the Node is
struct Node
{
    int data;
    struct Node* next;
};*/

/*You are required to complete this method */

Node* reverse(Node *) ;
bool isPalindrome(Node *head)
{
    if(head==NULL||head->next==NULL)
        return true ;
       
    Node *first,*second ;
    first=head ;
    second=head ;
   
    while(second!=NULL&&second->next!=NULL)
    {
        first=first->next ;
        second=second->next->next ;
    }
   
    Node *temp=head ;
    if(second==NULL)
    {
        while(temp->next!=first)
            temp=temp->next ;
    }
    else
    {
        while(temp!=first)
            temp=temp->next ;
    }
   
    Node *half ;
    half=temp->next ;
    temp->next=NULL ;
   
    half=reverse(half) ;
   
    while(head!=NULL&&half!=NULL)
    {
        if(head->data!=half->data)
            return false ;
        else
        {
            head=head->next ;
            half=half->next ;
        }
    }
    return true ;
}

Node* reverse(Node *head)
{
    if(head==NULL||head->next==NULL)
        return head ;
       
    Node *one,*two,*three ;
    one=head ;
    two=one->next ;
    three=two->next ;
   
    one->next=NULL ;
    two->next=one ;
   
    while(three!=NULL)
    {
        one=two ;
        two=three ;
        three=three->next ;
       
        two->next=one ;
    }
    return two ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )