GeeksforGeeks » Interview Questions

Amazon Interview Question for Software Engineer/Developer (0 - 2 Years)

(3 posts)
  • Started 4 months ago by Name:
  • Latest reply from Aashish Barnwal

Tags:

  1. Name:
    guest
    Posted 4 months ago #

    Question 3 / 3
    You are given a function isListPalindrome which takes in a singly linked list of integers. Complete the function given, return 1 if the linked list is a palindrome, else return 0.
    Sample Test Cases:

    Input #00:
    1->2->1

    Output #00:
    1

    Explanation:
    The linked list when reversed still reads as 1->2->1. Hence it's a palindrome, return 1;

  2. kartik
    Moderator
    Posted 4 months ago #

  3. Dedicated Programmer
    Member
    Posted 4 months ago #

    first reach the mid of the linked list through fast pointer slow pointer method,
    reverse the second half the linked list and take two pointers, one pointing to the head of the first part and another to the head of second part.
    increment both pointers if their data are same,repeat till we encounter Null.

    void ReverseLinkedList(struct node **start)
    {
    struct node *p=NULL,*q=*start,*r=NULL;
    while(q)
    {
    r=q->next;
    q->next=p;
    p=q;
    q=r;
    }
    *start=p;
    }

    int checkPalindrome(struct node *start)
    {
    struct node *fast=start,*slow=start;
    while(fast->next && fast->next->next)
    {
    fast=fast->next->next;
    slow=slow->next;
    }

    ReverseLinkedList(&(slow->next));
    fast=start;
    slow=slow->next;
    while(slow)
    {
    if(fast->data!=slow->data)
    return 0;
    fast=fast->next;
    slow=slow->next;
    }
    return 1;
    }

    correct me if mistaken.


Reply

You must log in to post.

RSS feed for this topic