Python Program To Check If A Linked List Of Strings Forms A Palindrome
Last Updated :
22 Jun, 2022
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.
The idea is very simple. Construct a string out of given linked list and check if the constructed string is palindrome or not.
Python
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def isPalindromeUtil( self , string):
return (string = = string[:: - 1 ])
def isPalindrome( self ):
node = self .head
temp = []
while (node is not None ):
temp.append(node.data)
node = node. next
string = "".join(temp)
return self .isPalindromeUtil(string)
def printList( self ):
temp = self .head
while (temp):
print temp.data,
temp = temp. next
llist = LinkedList()
llist.head = Node( 'a' )
llist.head. next = Node( 'bc' )
llist.head. next . next = Node( "d" )
llist.head. next . next . next = Node( "dcb" )
llist.head. next . next . next . next = Node( "a" )
print "true" if llist.isPalindrome() else "false"
|
Output:
true
Time Complexity: O(n), where n is the number of nodes in the given linked list.
Auxiliary Space: O(m), where m is the length of the string formed by the linked list.
Please refer complete article on Check if a linked list of strings forms a palindrome for more details!
Share your thoughts in the comments
Please Login to comment...