Program to check linked list items are forming palindrome or not in Python

Suppose we have a linked list. We have to check whether the list elements are forming a palindrome or not. So if the list element is like [5,4,3,4,5], then this is a palindrome, but a list like [5,4,3,2,1] is not a palindrome.

To solve this, we will follow these steps −

  • fast := head, slow := head, rev := None and flag := 1
  • if head is empty, then return true
  • while fast and next of fast is available
    • if next of the next of fast is available, then set flag := 0 and break the loop
    • fast := next of the next of fast
    • temp := slow, slow := next of slow
    • next of temp := rev, and rev := temp
  • fast := next of slow, and next of slow := rev
  • if flag is set, then slow := next of slow
  • while fast and slow are not None,
    • if value of fast is not same as value of slow, then return false
    • fast := next of fast, and slow := next of slow
  • return true

Let us see the following implementation to get better understanding −


 Live Demo

class ListNode:
   def __init__(self, data, next = None): = data = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
         ptr = = ListNode(element)
   return head
class Solution(object):
   def isPalindrome(self, head):
      fast,slow = head,head
      rev = None
      flag = 1
      if not head:
         return True
      while fast and
         if not
            flag = 0
      fast =
      temp = slow
      slow = = rev
      rev = temp
      fast = = rev
      if flag:
         slow =
         while fast and slow:
            if !=
               return False
      fast =
      slow =
      return True
      head = make_list([5,4,3,4,5])
ob1 = Solution()