Check if a linked list is a palindrome in Python
Here in this tutorial, we will learn how to check if a linked list is a palindrome or not in Python.
We can check if the given linked list is palindrome or not by returning 1 if it is and 0 if it is not for example:
Linked list 1:
1 2 3 2 1
Linked list 2:
1 24 2 5 3 2 3 6 4
Checking if a linked list is palindrome
class Node: def __init__(self, data): self.data = data self.next = None def takingInput(): head = tail = None list1 = [int(i) for i in input().split()] for i in list1: if i == -1: break NewNode = Node(i) if head == None: head = NewNode tail = NewNode else: tail.next = NewNode tail = NewNode return head def palindrome(head): curr = head list1 =  while curr: list1.append(curr.data) curr = curr.next while head: if head.data != list1.pop(): return False return True Head = takingInput() p = palindrome(Head) if p == True: print('1') else: print('0')
1 2 3 2 1 1
In the code above, we have first defined a node class and then written an essential function to take inputs for our linked list.
Moving forward we have defined our main function that is ‘palindrome()’ in which we take one argument that is the head of the linked list. Inside the function, we have taken a curr variable and an empty list into which we have appended all the elements of the linked list.
Then while the head is not equal to none we have popped out one element of the list starting from the end and compared it with the head and if the data does not match then we have returned false otherwise true.
Hence we have seen how to check if the linked list is palindrome or not.
Leave a Reply