Python Program To Check If A Singly Linked List Is Palindrome
Last Updated :
22 Feb, 2023
Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false.

METHOD 1 (Use a Stack):
- A simple solution is to use a stack of list nodes. This mainly involves three steps.
- Traverse the given list from head to tail and push every visited node to stack.
- Traverse the list again. For every visited node, pop a node from the stack and compare data of popped node with the currently visited node.
- If all nodes matched, then return true, else false.
Below image is a dry run of the above approach:

Below is the implementation of the above approach :
Python3
# Python3 program to check if linked
# list is palindrome using stack
class Node:
def __init__(self, data):
self.data = data
self.ptr = None
# Function to check if the linked list
# is palindrome or not
def ispalindrome(head):
# Temp pointer
slow = head
# Declare a stack
stack = []
ispalin = True
# Push all elements of the list
# to the stack
while slow != None:
stack.append(slow.data)
# Move ahead
slow = slow.ptr
# Iterate in the list again and
# check by popping from the stack
while head != None:
# Get the top most element
i = stack.pop()
# Check if data is not
# same as popped element
if head.data == i:
ispalin = True
else:
ispalin = False
break
# Move ahead
head = head.ptr
return ispalin
# Driver Code
# Addition of linked list
one = Node(1)
two = Node(2)
three = Node(3)
four = Node(4)
five = Node(3)
six = Node(2)
seven = Node(1)
# Initialize the next pointer
# of every current pointer
one.ptr = two
two.ptr = three
three.ptr = four
four.ptr = five
five.ptr = six
six.ptr = seven
seven.ptr = None
# Call function to check
# palindrome or not
result = ispalindrome(one)
print("isPalindrome:", result)
# This code is contributed by Nishtha Goel
Output:
isPalindrome: true
Time complexity: O(n), where n represents the length of the given linked list.
Auxiliary Space: O(n), for using a stack, where n represents the length of the given linked list.
METHOD 2 (By reversing the list):
This method takes O(n) time and O(1) extra space.
1) Get the middle of the linked list.
2) Reverse the second half of the linked list.
3) Check if the first half and second half are identical.
4) Construct the original linked list by reversing the second half again and attaching it back to the first half
To divide the list into two halves, method 2 of this post is used.
When a number of nodes are even, the first and second half contain exactly half nodes. The challenging thing in this method is to handle the case when the number of nodes is odd. We don't want the middle node as part of the lists as we are going to compare them for equality. For odd cases, we use a separate variable 'midnode'.
Python3
# Python program to check if
# linked list is palindrome
# Node class
class Node:
# Constructor to initialize
# the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to check if given
# linked list is palindrome or not
def isPalindrome(self, head):
slow_ptr = head
fast_ptr = head
prev_of_slow_ptr = head
# To handle odd size list
midnode = None
# Initialize result
res = True
if (head != None and
head.next != None):
# Get the middle of the list.
# Move slow_ptr by 1 and
# fast_ptrr by 2, slow_ptr
# will have the middle node
while (fast_ptr != None and
fast_ptr.next != None):
# We need previous of the slow_ptr
# for linked lists with odd
# elements
fast_ptr = fast_ptr.next.next
prev_of_slow_ptr = slow_ptr
slow_ptr = slow_ptr.next
# fast_ptr would become NULL when
# there are even elements in the
# list and not NULL for odd elements.
# We need to skip the middle node for
# odd case and store it somewhere so
# that we can restore the original list
if (fast_ptr != None):
midnode = slow_ptr
slow_ptr = slow_ptr.next
# Now reverse the second half
# and compare it with the first half
second_half = slow_ptr
# NULL terminate first half
prev_of_slow_ptr.next = None
# Reverse the second half
second_half = self.reverse(second_half)
# Compare
res = self.compareLists(head, second_half)
# Construct the original list back
# Reverse the second half again
second_half = self.reverse(second_half)
if (midnode != None):
# If there was a mid node (odd size
# case) which was not part of either
# first half or second half.
prev_of_slow_ptr.next = midnode
midnode.next = second_half
else:
prev_of_slow_ptr.next = second_half
return res
# Function to reverse the linked list
# Note that this function may change
# the head
def reverse(self, second_half):
prev = None
current = second_half
next = None
while current != None:
next = current.next
current.next = prev
prev = current
current = next
second_half = prev
return second_half
# Function to check if two input
# lists have same data
def compareLists(self, head1, head2):
temp1 = head1
temp2 = head2
while (temp1 and temp2):
if (temp1.data == temp2.data):
temp1 = temp1.next
temp2 = temp2.next
else:
return 0
# Both are empty return 1
if (temp1 == None and temp2 == None):
return 1
# Will reach here when one is NULL
# and other is not
return 0
# Function to insert a new node
# at the beginning
def push(self, new_data):
# Allocate the Node &
# Put in the data
new_node = Node(new_data)
# Link the old list of the new one
new_node.next = self.head
# Move the head to point to the
# new Node
self.head = new_node
# A utility function to print
# a given linked list
def printList(self):
temp = self.head
while(temp):
print(temp.data, end = "->")
temp = temp.next
print("NULL")
# Driver code
if __name__ == '__main__':
l = LinkedList()
s = ['a', 'b', 'a',
'c', 'a', 'b', 'a']
for i in range(7):
l.push(s[i])
l.printList()
if (l.isPalindrome(l.head) != False):
print("Is Palindrome")
else:
print("Not Palindrome")
print()
# This code is contributed by MuskanKalra1
Output:
a->NULL
Is Palindrome
b->a->NULL
Not Palindrome
a->b->a->NULL
Is Palindrome
c->a->b->a->NULL
Not Palindrome
a->c->a->b->a->NULL
Not Palindrome
b->a->c->a->b->a->NULL
Not Palindrome
a->b->a->c->a->b->a->NULL
Is Palindrome
Time Complexity: O(n)
Auxiliary Space: O(1)
Please refer complete article on Function to check if a singly linked list is palindrome for more details!
Similar Reads
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 For Checking Linked List With A Loop Is Palindrome Or Not
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
4 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 to check if given string is vowel Palindrome
Given a string (may contain both vowel and consonant letters), remove all consonants, then check if the resulting string is palindrome or not. Examples: Input : abcuhuvmnba Output : YES Explanation : The consonants in the string "abcuhuvmnba" are removed. Now the string becomes "auua". Input : xayzu
5 min read
Python Program To Check String Is Palindrome Using Stack
A palindrome is a sequence of characters that reads the same backward as forward. Checking whether a given string is a palindrome is a common programming task. In this article, we will explore how to implement a Python program to check if a string is a palindrome using a stack. Example Input: str =
3 min read
Python Program To Check If Two Linked Lists Are Identical
Two Linked Lists are identical when they have the same data and the arrangement of data is also the same. For example, Linked lists a (1->2->3) and b(1->2->3) are identical. . Write a function to check if the given two linked lists are identical. Recommended: Please solve it on "PRACTICE
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 Swapping Nodes In A Linked List Without Swapping Data
Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10->15-
5 min read
Python Program For Rearranging A Given Linked List In-Place
Given a singly linked list L0 -> L1 -> ⦠-> Ln-1 -> Ln. Rearrange the nodes in the list so that the new formed list is: L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 ...You are required to do this in place without altering the nodes' values. Examples: Input: 1 -> 2 -> 3 ->
6 min read