In thisprogram we will see how to check if the linked list is palindrome or not.
Input: 10=>20=>30=>20=>10
Output: True
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def length(self):
temp = self.head
count = 0
while temp!=None:
count = count+1
temp=temp.next
return count
def IterativeSearch(self,index):
temp = self.head
count = 1
len = self.length()
while temp!=None:
#print("This loop is running for",temp.data,"and value of count at this pos is",count)
if count == index:
#count=count+1
return temp.data
else:
count=count+1
temp = temp.next
if count>len:
return 0
def checkPalindrome(self):
len = self.length()
flag = 0
if len%2==0:
flag = len/2
else:
flag = (len-1)/2
start_counter = 1
counter = 0
while start_counter<=flag:
if self.IterativeSearch(start_counter)==self.IterativeSearch(len) :
counter=counter+1
start_counter = start_counter+1
len = len-1
else:
return False
if counter==flag:
return True
if __name__=="__main__":
llist = LinkedList()
first = Node(10)
second = Node(10)
third = Node(10)
fourth = Node(10)
fifth = Node(10)
llist.head = first
first.next = second
second.next = third
third.next = fourth
fourth.next = fifth
print(llist.checkPalindrome())
No comments:
Post a Comment