Given a linked list with a loop, the task is to find whether it is palindrome or not. You are not allowed to remove the loop.
Examples:
Input : 1 -> 2 -> 3 -> 2
             /|\      \|/
               ------- 1  
Output: Palindrome
Linked list is 1 2 3 2 1 which is a 
palindrome.
Input : 1 -> 2 -> 3 -> 4
             /|\      \|/
               ------- 1  
Output: Not Palindrome
Linked list is 1 2 3 4 1 which is a 
not palindrome. 
Algorithm:
Below is the implementation.
C++
| // C++ program to check if a linked list with// loop is palindrome or not.#include<bits/stdc++.h>usingnamespacestd;/* Link list node */structNode{    intdata;    structNode * next;};/* Function to find loop starting node.loop_node --> Pointer to one of the loop nodeshead --> Pointer to the start node of the linked list */Node* getLoopstart(Node *loop_node, Node *head){    Node *ptr1 = loop_node;    Node *ptr2 = loop_node;    // Count the number of nodes in loop    unsigned intk = 1, i;    while(ptr1->next != ptr2)    {        ptr1 = ptr1->next;        k++;    }    // Fix one pointer to head    ptr1 = head;    // And the other pointer to k nodes after head    ptr2 = head;    for(i = 0; i < k; i++)        ptr2 = ptr2->next;    /* Move both pointers at the same pace,    they will meet at loop starting node */    while(ptr2 != ptr1)    {        ptr1 = ptr1->next;        ptr2 = ptr2->next;    }    returnptr1;}/* This function detects and find loop starting  node  in the list*/Node* detectAndgetLoopstarting(Node *head){    Node *slow_p = head, *fast_p = head,*loop_start;    //Start traversing list and detect loop    while(slow_p && fast_p && fast_p->next)    {        slow_p = slow_p->next;        fast_p = fast_p->next->next;        /* If slow_p and fast_p meet then find           the loop starting node*/        if(slow_p == fast_p)        {            loop_start = getLoopstart(slow_p, head);            break;        }    }    // Return starting node of loop    returnloop_start;}// Utility function to check if a linked list with loop// is palindrome with given starting point.boolisPalindromeUtil(Node *head, Node* loop_start){    Node *ptr = head;    stack<int> s;    // Traverse linked list until last node is equal    // to loop_start and store the elements till start    // in a stack    intcount = 0;    while(ptr != loop_start || count != 1)    {        s.push(ptr->data);        if(ptr == loop_start)            count = 1;        ptr = ptr->next;    }    ptr = head;    count = 0;    // Traverse linked list until last node is    // equal to loop_start second time    while(ptr != loop_start || count != 1)    {        // Compare data of node with the top of stack        // If equal then continue        if(ptr->data == s.top())            s.pop();        // Else return false        else            returnfalse;        if(ptr == loop_start)            count = 1;        ptr = ptr->next;    }    // Return true if linked list is palindrome    returntrue;}// Function to find if linked list is palindrome or notboolisPalindrome(Node* head){    // Find the loop starting node    Node* loop_start = detectAndgetLoopstarting(head);    // Check if linked list is palindrome    returnisPalindromeUtil(head, loop_start);}Node *newNode(intkey){    Node *temp = newNode;    temp->data = key;    temp->next = NULL;    returntemp;}/* Driver program to test above function*/intmain(){    Node *head = newNode(50);    head->next = newNode(20);    head->next->next = newNode(15);    head->next->next->next = newNode(20);    head->next->next->next->next = newNode(50);    /* Create a loop for testing */    head->next->next->next->next->next = head->next->next;    isPalindrome(head)? cout << "\nPalindrome"                     : cout << "\nNot Palindrome";    return0;} | 
Java
| // Java program to check if a linked list// with loop is palindrome or not.importjava.util.*;classGfG {/* Link list node */staticclassNode {     intdata;     Node next; }/* Function to find loop starting node. loop_node --> Pointer to one of the loop nodes head --> Pointer to the start node of the linked list */staticNode getLoopstart(Node loop_node,                             Node head) {     Node ptr1 = loop_node;     Node ptr2 = loop_node;     // Count the number of nodes in loop     intk = 1, i;     while(ptr1.next != ptr2)     {         ptr1 = ptr1.next;         k++;     }     // Fix one pointer to head     ptr1 = head;     // And the other pointer to k     // nodes after head     ptr2 = head;     for(i = 0; i < k; i++)         ptr2 = ptr2.next;     /* Move both pointers at the same pace,     they will meet at loop starting node */    while(ptr2 != ptr1)     {         ptr1 = ptr1.next;         ptr2 = ptr2.next;     }     returnptr1; } /* This function detects and find loop starting node in the list*/staticNode detectAndgetLoopstarting(Node head) {     Node slow_p = head, fast_p = head,loop_start = null;     //Start traversing list and detect loop     while(slow_p != null&& fast_p != null&&             fast_p.next != null)     {         slow_p = slow_p.next;         fast_p = fast_p.next.next;         /* If slow_p and fast_p meet then find         the loop starting node*/        if(slow_p == fast_p)         {             loop_start = getLoopstart(slow_p, head);             break;         }     }     // Return starting node of loop     returnloop_start; } // Utility function to check if  // a linked list with loop is // palindrome with given starting point. staticbooleanisPalindromeUtil(Node head,                            Node loop_start) {     Node ptr = head;     Stack<Integer> s = newStack<Integer> ();     // Traverse linked list until last node      // is equal to loop_start and store the      // elements till start in a stack     intcount = 0;     while(ptr != loop_start || count != 1)     {         s.push(ptr.data);         if(ptr == loop_start)             count = 1;         ptr = ptr.next;     }     ptr = head;     count = 0;     // Traverse linked list until last node is     // equal to loop_start second time     while(ptr != loop_start || count != 1)     {         // Compare data of node with the top of stack         // If equal then continue         if(ptr.data == s.peek())             s.pop();         // Else return false         else            returnfalse;         if(ptr == loop_start)             count = 1;         ptr = ptr.next;     }     // Return true if linked list is palindrome     returntrue; } // Function to find if linked list// is palindrome or not staticbooleanisPalindrome(Node head) {     // Find the loop starting node     Node loop_start = detectAndgetLoopstarting(head);     // Check if linked list is palindrome     returnisPalindromeUtil(head, loop_start); } staticNode newNode(intkey) {     Node temp = newNode();     temp.data = key;     temp.next = null;     returntemp; } /* Driver code*/publicstaticvoidmain(String[] args) {     Node head = newNode(50);     head.next = newNode(20);     head.next.next = newNode(15);     head.next.next.next = newNode(20);     head.next.next.next.next = newNode(50);     /* Create a loop for testing */    head.next.next.next.next.next = head.next.next;     if(isPalindrome(head) == true)        System.out.println("Palindrome");    else        System.out.println("Not Palindrome"); }} // This code is contributed by prerna saini | 
Python
| # Python3 program to check if a linked list# with loop is palindrome or not.# Node class classNode:     # Constructor to initialize the node object     def__init__(self, data):         self.data =data         self.next=None# Function to find loop starting node. # loop_node -. Pointer to one of # the loop nodes head -. Pointer to # the start node of the linked listdefgetLoopstart(loop_node,head):     ptr1 =loop_node     ptr2 =loop_node     # Count the number of nodes in loop     k =1    i =0    while(ptr1.next!=ptr2):             ptr1 =ptr1.next        k =k +1        # Fix one pointer to head     ptr1 =head     # And the other pointer to k     # nodes after head     ptr2 =head    i =0    while( i < k ) :        ptr2 =ptr2.next        i =i +1    # Move both pointers at the same pace,     #they will meet at loop starting node */    while(ptr2 !=ptr1):             ptr1 =ptr1.next        ptr2 =ptr2.next        returnptr1 # This function detects and find # loop starting node in the listdefdetectAndgetLoopstarting(head):     slow_p =head    fast_p =head    loop_start =None    # Start traversing list and detect loop     while(slow_p !=Noneandfast_p !=Noneand            fast_p.next!=None) :            slow_p =slow_p.next        fast_p =fast_p.next.next        # If slow_p and fast_p meet then find         # the loop starting node        if(slow_p ==fast_p) :                    loop_start =getLoopstart(slow_p, head)             break            # Return starting node of loop     returnloop_start # Utility function to check if # a linked list with loop is # palindrome with given starting point. defisPalindromeUtil(head, loop_start):     ptr =head     s =[]     # Traverse linked list until last node     # is equal to loop_start and store the     # elements till start in a stack     count =0    while(ptr !=loop_start orcount !=1):             s.append(ptr.data)         if(ptr ==loop_start) :            count =1        ptr =ptr.next        ptr =head     count =0    # Traverse linked list until last node is     # equal to loop_start second time     while(ptr !=loop_start orcount !=1):             # Compare data of node with the top of stack         # If equal then continue         if(ptr.data ==s[-1]):             s.pop()         # Else return False         else:            returnFalse        if(ptr ==loop_start) :            count =1        ptr =ptr.next        # Return True if linked list is palindrome     returnTrue# Function to find if linked list# is palindrome or not defisPalindrome(head) :    # Find the loop starting node     loop_start =detectAndgetLoopstarting(head)     # Check if linked list is palindrome     returnisPalindromeUtil(head, loop_start) defnewNode(key) :    temp =Node(0)     temp.data =key     temp.next=None    returntemp # Driver codehead =newNode(50) head.next=newNode(20) head.next.next=newNode(15) head.next.next.next=newNode(20) head.next.next.next.next=newNode(50) # Create a loop for testing head.next.next.next.next.next=head.next.nextif(isPalindrome(head) ==True):    print("Palindrome")else:    print("Not Palindrome") # This code is contributed by Arnab Kundu | 
C#
| // C# program to check if a linked list// with loop is palindrome or not.usingSystem;usingSystem.Collections.Generic; classGfG {/* Link list node */classNode {     publicintdata;     publicNode next; }/* Function to find loop starting node. loop_node --> Pointer to one of the loop nodes head --> Pointer to the start node of the linked list */staticNode getLoopstart(Node loop_node,                             Node head) {     Node ptr1 = loop_node;     Node ptr2 = loop_node;     // Count the number of nodes in loop     intk = 1, i;     while(ptr1.next != ptr2)     {         ptr1 = ptr1.next;         k++;     }     // Fix one pointer to head     ptr1 = head;     // And the other pointer to k     // nodes after head     ptr2 = head;     for(i = 0; i < k; i++)         ptr2 = ptr2.next;     /* Move both pointers at the same pace,     they will meet at loop starting node */    while(ptr2 != ptr1)     {         ptr1 = ptr1.next;         ptr2 = ptr2.next;     }     returnptr1; } /* This function detects and find loop starting node in the list*/staticNode detectAndgetLoopstarting(Node head) {     Node slow_p = head, fast_p = head,loop_start = null;     //Start traversing list and detect loop     while(slow_p != null&& fast_p != null&&             fast_p.next != null)     {         slow_p = slow_p.next;         fast_p = fast_p.next.next;         /* If slow_p and fast_p meet then find         the loop starting node*/        if(slow_p == fast_p)         {             loop_start = getLoopstart(slow_p, head);             break;         }     }     // Return starting node of loop     returnloop_start; } // Utility function to check if // a linked list with loop is // palindrome with given starting point. staticboolisPalindromeUtil(Node head,                            Node loop_start) {     Node ptr = head;     Stack<int> s = newStack<int> ();     // Traverse linked list until last node     // is equal to loop_start and store the     // elements till start in a stack     intcount = 0;     while(ptr != loop_start || count != 1)     {         s.Push(ptr.data);         if(ptr == loop_start)             count = 1;         ptr = ptr.next;     }     ptr = head;     count = 0;     // Traverse linked list until last node is     // equal to loop_start second time     while(ptr != loop_start || count != 1)     {         // Compare data of node with the top of stack         // If equal then continue         if(ptr.data == s.Peek())             s.Pop();         // Else return false         else            returnfalse;         if(ptr == loop_start)             count = 1;         ptr = ptr.next;     }     // Return true if linked list is palindrome     returntrue; } // Function to find if linked list// is palindrome or not staticboolisPalindrome(Node head) {     // Find the loop starting node     Node loop_start = detectAndgetLoopstarting(head);     // Check if linked list is palindrome     returnisPalindromeUtil(head, loop_start); } staticNode newNode(intkey) {     Node temp = newNode();     temp.data = key;     temp.next = null;     returntemp; } /* Driver code*/publicstaticvoidMain(String[] args) {     Node head = newNode(50);     head.next = newNode(20);     head.next.next = newNode(15);     head.next.next.next = newNode(20);     head.next.next.next.next = newNode(50);     /* Create a loop for testing */    head.next.next.next.next.next = head.next.next;     if(isPalindrome(head) == true)        Console.WriteLine("Palindrome");    else        Console.WriteLine("Not Palindrome"); }}/* This code is contributed by 29AjayKumar */ | 
Javascript
| <script>// javascript program to check if a linked list// with loop is palindrome or not.class GfG {    /* Link list node */    class Node {        constructor() {            this.data = 0;            this.next = null;        }    }    /*     * Function to find loop starting node. loop_node --> Pointer to one of the loop     * nodes head --> Pointer to the start node of the linked list     */    functiongetLoopstart(loop_node,  head) {        varptr1 = loop_node;        varptr2 = loop_node;        // Count the number of nodes in loop        vark = 1, i;        while(ptr1.next != ptr2) {            ptr1 = ptr1.next;            k++;        }        // Fix one pointer to head        ptr1 = head;        // And the other pointer to k        // nodes after head        ptr2 = head;        for(i = 0; i < k; i++)            ptr2 = ptr2.next;        /*         * Move both pointers at the same pace, they will meet at loop starting node         */        while(ptr2 != ptr1) {            ptr1 = ptr1.next;            ptr2 = ptr2.next;        }        returnptr1;    }    /*     * This function detects and find loop starting node in the list     */    functiondetectAndgetLoopstarting(head) {        varslow_p = head, fast_p = head, loop_start = null;        // Start traversing list and detect loop        while(slow_p != null&& fast_p != null&& fast_p.next != null) {            slow_p = slow_p.next;            fast_p = fast_p.next.next;            /*             * If slow_p and fast_p meet then find the loop starting node             */            if(slow_p == fast_p) {                loop_start = getLoopstart(slow_p, head);                break;            }        }        // Return starting node of loop        returnloop_start;    }    // Utility function to check if    // a linked list with loop is    // palindrome with given starting point.    functionisPalindromeUtil(head,  loop_start) {        varptr = head;        vars =  [];        // Traverse linked list until last node        // is equal to loop_start and store the        // elements till start in a stack        varcount = 0;        while(ptr != loop_start || count != 1) {            s.push(ptr.data);            if(ptr == loop_start)                count = 1;            ptr = ptr.next;        }        ptr = head;        count = 0;        // Traverse linked list until last node is        // equal to loop_start second time        while(ptr != loop_start || count != 1) {            // Compare data of node with the top of stack            // If equal then continue            varstk = s.pop();            if(ptr.data == stk);                            // Else return false            else{            s.push(stk);                returnfalse;                }            if(ptr == loop_start)                count = 1;            ptr = ptr.next;        }        // Return true if linked list is palindrome        returntrue;    }    // Function to find if linked list    // is palindrome or not    functionisPalindrome(head) {        // Find the loop starting node        varloop_start = detectAndgetLoopstarting(head);        // Check if linked list is palindrome        returnisPalindromeUtil(head, loop_start);    }    functionnewNode(key) {        vartemp = newNode();        temp.data = key;        temp.next = null;        returntemp;    }    /* Driver code */            varhead = newNode(50);        head.next = newNode(20);        head.next.next = newNode(15);        head.next.next.next = newNode(20);        head.next.next.next.next = newNode(50);        /* Create a loop for testing */        head.next.next.next.next.next = head.next.next;        if(isPalindrome(head) == true)            document.write("Palindrome");        else            document.write("Not Palindrome");// This code contributed by aashish1995 </script> | 
Palindrome
Time Complexity: O(n) 
Auxiliary Space: O(n) 
This article is contributed by Sahil Chhabra (akku). If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    








