In this method, we’ll have two pointers p and q. p will initially point to the head of the list and q to the last node of the list. Next, we’ll check the data elements at each of these nodes that are being pointed to by p and q and see if they are equal to each other. If they are, we’ll progress p by one, and we’ll move q by one in reverse until we get to a point where p and q either meet or essentially can’t move any further without crossing.
Implementation
Let’s jump to the coding part now.
xxxxxxxxxx
def is_palindrome(self):
if self.head:
p = self.head
q = self.head
prev = []
i = 0
while q:
prev.append(q)
q = q.next
i += 1
q = prev[i-1]
count = 1
while count <= i//2 + 1:
if prev[-count].data != p.data:
return False
p = p.next
count += 1
return True
else:
return True