Open In App

Python Program To Check If A Singly Linked List Is Palindrome

Last Updated : 22 Feb, 2023
Comments
Improve
Suggest changes
2 Likes
Like
Report

Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false.

Palindrome Linked List

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 : 

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'. 

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!


Next Article

Similar Reads