Python Program to Check whether a Singly Linked List is a Palindrome

PythonServer Side ProgrammingProgramming

When it is required to check if a singly linked list is a palindrome or not, methods to add an element, get the previous node and to check if a palindrome is formed are defined.

Below is a demonstration of the same −


 Live Demo

class Node:
   def __init__(self, data): = data = None

class LinkedList_struct:
   def __init__(self):
      self.head = None
      self.last_node = None

   def add_elements(self, data):
      if self.last_node is None:
         self.head = Node(data)
         self.last_node = self.head
      else: = Node(data)
         self.last_node =

   def get_previous_node(self, ref_node):
      curr = self.head
      while (curr and != ref_node):
         curr =
         return curr

def check_palindrome(my_list):
   beg = my_list.head
   end = my_list.last_node
   while (beg != end and != beg):
      if !=
         return False
      beg =
      end = my_list.get_previous_node(end)
   return True

my_instance = LinkedList_struct()

my_input = input('Enter elements to the linked list: ').split()
for data in my_input:

if check_palindrome(my_instance):
   print('The linked list is palindromic in nature')
   print('The linked list is not palindromic in nature')


Enter elements to the linked list: 89 90 78 90 89
The linked list is palindromic in nature


  • The ‘Node’ class is created.

  • Another ‘LinkedList_struct’ class with required attributes is created.

  • It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’ and last node to ‘None’.

  • Another method named ‘add_elements’ is defined, that is used to fetch the previous node in the linked list.

  • Another method named ‘get_previous_node’ is defined that is used to display the linked list data on the console.

  • A method named ‘check_palindrome’ is defined, that compares the first and last element, if they are not same, it determines that the list wasn’t palindromic in nature.

  • An object of the ‘LinkedList_struct’ class is created.

  • The user input is taken for the elements in the linked list.

  • The elements are added to the linked list.

  • The ‘check_palindrome’ method is called on this linked list.

  • Relevant output is displayed on the console.

Published on 15-Apr-2021 13:26:37