I have found a recursive solution to check whether a linked list is a palindrome:
def isPalindrome(self, head: ListNode) -> bool: self.front_pointer = head def recursively_check(head): if head: if not recursively_check(head.next): return False if self.front_pointer.val != head.val: return False self.front_pointer = self.front_pointer.next return True return recursively_check()
'if head' statement:
Why are we returning False for the first if statement, when "recursively_check(head.next)" points to None? This would be okay, no? Because it simply means we’ve reached the end of the linked list, or am I reading this wrongly?
For the second if statement, this kind of makes sense- in my mind it is checking the first node
front_pointer and the last node
head are the same?
Then we are simply moving the front_pointer, which initially points to the head of the linked list to the next node to check? But while I understand this, from the back end, how are we moving from the last node to the second last node?
Finally, why do we return the recursive call
recursively_check()? I don’t see when we will reach this code- as we would have returned True or False by the time we reach here, no?
Source: Python Questions