top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Write a C function with constant space complexity to tell whether a singly linked list is palindrome or not?

+1 vote
163 views
Write a C function with constant space complexity to tell whether a singly linked list is palindrome or not?
posted May 25, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Reversing the list,this method takes O(n) time and O(1) extra space.
1) Get the middle of the linked list.
2) Reverse the second half of the linked list.
3) Check if the first half and second half are identical.
4) Construct the original linked list by reversing the second half again and attaching it back to the first half
To divide the list in two halves, method 2 of this post is used.
When number of nodes are even, the first and second half contain exactly half nodes. The challenging thing in this method is to handle the case when number of nodes are odd. We don’t want the middle node as part of any of the lists as we are going to compare them for equality. For odd case, we use a separate variable ‘midnode’.

/* Program to check if a linked list is palindrome */
    #include<stdio.h>
    #include<stdlib.h>
    #include<stdbool.h>

    /* Link list node */
    struct node
    {
        char data;
        struct node* next;
    };

    void reverse(struct node**);
    bool compareLists(struct node*, struct node *);

    /* Function to check if given linked list is
      palindrome or not */
    bool isPalindrome(struct node *head)
    {
        struct node *slow_ptr = head, *fast_ptr = head;
        struct node *second_half, *prev_of_slow_ptr = head;
        struct node *midnode = NULL;  // To handle odd size list
        bool res = true; // initialize result

        if (head!=NULL && head->next!=NULL)
        {
            /* Get the middle of the list. Move slow_ptr by 1
              and fast_ptrr by 2, slow_ptr will have the middle
              node */
            while (fast_ptr != NULL && fast_ptr->next != NULL)
            {
                fast_ptr = fast_ptr->next->next;

                /*We need previous of the slow_ptr for
                 linked lists  with odd elements */
                prev_of_slow_ptr = slow_ptr;
                slow_ptr = slow_ptr->next;
            }


            /* fast_ptr would become NULL when there are even elements in list. 
               And not NULL for odd elements. We need to skip the middle node 
               for odd case and store it somewhere so that we can restore the
               original list*/
            if (fast_ptr != NULL)
            {
                midnode = slow_ptr;
                slow_ptr = slow_ptr->next;
            }

            // Now reverse the second half and compare it with first half
            second_half = slow_ptr;
            prev_of_slow_ptr->next = NULL; // NULL terminate first half
            reverse(&second_half);  // Reverse the second half
            res = compareLists(head, second_half); // compare

            /* Construct the original list back */
             reverse(&second_half); // Reverse the second half again
             if (midnode != NULL)  // If there was a mid node (odd size case) which                                                         
                                   // was not part of either first half or second half.
             {
                prev_of_slow_ptr->next = midnode;
                midnode->next = second_half;
             }
             else  prev_of_slow_ptr->next = second_half;
        }
        return res;
    }

    /* Function to reverse the linked list  Note that this
        function may change the head */
    void reverse(struct node** head_ref)
    {
        struct node* prev   = NULL;
        struct node* current = *head_ref;
        struct node* next;
        while (current != NULL)
        {
            next  = current->next;
            current->next = prev;
            prev = current;
            current = next;
        }
        *head_ref = prev;
    }

    /* Function to check if two input lists have same data*/
    bool compareLists(struct node* head1, struct node *head2)
    {
        struct node* temp1 = head1;
        struct node* temp2 = head2;

        while (temp1 && temp2)
        {
            if (temp1->data == temp2->data)
            {
                temp1 = temp1->next;
                temp2 = temp2->next;
            }
            else return 0;
        }

        /* Both are empty reurn 1*/
        if (temp1 == NULL && temp2 == NULL)
            return 1;

        /* Will reach here when one is NULL
          and other is not */
        return 0;
    }

    /* Push a node to linked list. Note that this function
      changes the head */
    void push(struct node** head_ref, char new_data)
    {
        /* allocate node */
        struct node* new_node =
            (struct node*) malloc(sizeof(struct node));

        /* put in the data  */
        new_node->data  = new_data;

        /* link the old list off the new node */
        new_node->next = (*head_ref);

        /* move the head to pochar to the new node */
        (*head_ref)    = new_node;
    }

    // A utility function to print a given linked list
    void printList(struct node *ptr)
    {
        while (ptr != NULL)
        {
            printf("%c->", ptr->data);
            ptr = ptr->next;
        }
        printf("NULL\n");
    }


    /* Drier program to test above function*/
    int main()
    {
        /* Start with the empty list */
        struct node* head = NULL;
        char str[] = "abacaba";
        int i;

        for (i = 0; str[i] != '\0'; i++)
        {
           push(&head, str[i]);
           printList(head);
           isPalindrome(head)? printf("Is Palindrome\n\n"):
                               printf("Not Palindrome\n\n");
        }

        return 0;
    }

Reference: http://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/

answer May 26, 2016 by Shivam Kumar Pandey
Similar Questions
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...