Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program For Finding The Length Of Loop In Linked List
Next article icon

Python Program For Checking Linked List With A Loop Is Palindrome Or Not

Last Updated : 19 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Detect the loop using the Floyd Cycle Detection Algorithm.
  2. Then find the starting node of the loop as discussed in this.
  3. Check the linked list is palindrome or not as discussed in this.

Below is the implementation. 

Python
# Python3 program to check if a  # linked list with loop is palindrome  # or not.  # Node class  class Node:       # 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 list def getLoopstart(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          return ptr1   # This function detects and find  # loop starting node in the list def detectAndgetLoopstarting(head):      slow_p = head     fast_p = head     loop_start = None      # Start traversing list and detect loop      while (slow_p != None and fast_p != None and            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      return loop_start   # Utility function to check if  # a linked list with loop is  # palindrome with given starting point.  def isPalindromeUtil(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 or count != 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 or count != 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:             return False          if (ptr == loop_start) :             count = 1         ptr = ptr.next          # Return True if linked list is      # palindrome      return True  # Function to find if linked list # is palindrome or not  def isPalindrome(head):      # Find the loop starting node      loop_start =      detectAndgetLoopstarting(head)       # Check if linked list is palindrome      return isPalindromeUtil(head,                              loop_start)   def newNode(key):     temp = Node(0)      temp.data = key      temp.next = None     return temp   # Driver code 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):     print("Palindrome") else:     print("Not Palindrome")  # This code is contributed by Arnab Kundu 

Output:  

Palindrome

Time Complexity: O(n) where n is no of nodes in the linked list

Auxiliary Space: O(n)

Please refer complete article on Check linked list with a loop is palindrome or not for more details!


Next Article
Python Program For Finding The Length Of Loop In Linked List
author
kartik
Improve
Article Tags :
  • Linked List
  • Python Programs
  • DSA
  • palindrome
Practice Tags :
  • Linked List
  • palindrome

Similar Reads

  • Python Program To Check If A Singly Linked List Is Palindrome
    Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. METHOD 1 (Use a Stack): A simple solution is to use a stack of list nodes. This mainly invol
    6 min read
  • Python Program To Check If A Linked List Of Strings Forms A Palindrome
    Given a linked list handling string data, check to see whether data is palindrome or not? Examples: Input: a -> bc -> d -> dcb -> a -> NULL Output: True String "abcddcba" is palindrome. Input: a -> bc -> d -> ba -> NULL Output: False String "abcdba" is not palindrome. Reco
    2 min read
  • Python Program to Check if a String is Palindrome or Not
    The task of checking if a string is a palindrome in Python involves determining whether a string reads the same forward as it does backward. For example, the string "madam" is a palindrome because it is identical when reversed, whereas "hello" is not. Using two pointer techniqueThis approach involve
    3 min read
  • Python program to check if number is palindrome (one-liner)
    In this article, we are given a number and we have to check whether the number is palindrome or not in one-liner code. The output will be True if it's a Palindrome number otherwise it would be False. Let's discuss how to find whether a number is palindrome or not in this article. Input1: test_number
    3 min read
  • Python Program For Finding The Length Of Loop In Linked List
    Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0. Re
    4 min read
  • Python Program For Pairwise Swapping Elements Of A Given Linked List
    Given a singly linked list, write a function to swap elements pairwise. Input: 1->2->3->4->5->6->NULL Output: 2->1->4->3->6->5->NULL Input: 1->2->3->4->5->NULL Output: 2->1->4->3->5->NULL Input: 1->NULL Output: 1->NULL For examp
    2 min read
  • Python Program For Pairwise Swapping Elements Of A Given Linked List By Changing Links
    Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function sh
    4 min read
  • Python Program For Finding The Middle Element Of A Given Linked List
    Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list
    4 min read
  • Python Program to find all Palindromic Bitlists in length
    In this article, we will learn to generate all Palindromic Bitlists of a given length using Backtracking in Python. Backtracking can be defined as a general algorithmic technique that considers searching every possible combination in order to solve a computational problem. Whereas, Bitlists are list
    6 min read
  • Python Program For In-Place Merge Two Linked Lists Without Changing Links Of First List
    Given two sorted singly linked lists having n and m elements each, merge them using constant space. First, n smallest elements in both the lists should become part of the first list and the rest elements should be part of the second list. Sorted order should be maintained. We are not allowed to chan
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences