Back to course home
0% completed
Vote For New Content
I don't think that checking the None's at the end of the isPalindrome are neccessary
Michał Sabiniarz
Sep 15, 2024
Please correct me if I'm wrong but to me it looks like the code for isPalindrome could be simpler. If I'm wrong please supply me a test for which it would fail
class Solution: def isPalindrome(self, head): mid = self.find_mid(head) reversed = self.reverse(mid) node = head original_reversed_head = reversed while reversed: if reversed.val != node.val: return False reversed = reversed.next node = node.next # Restore linked list self.reverse(original_reversed_head) return True def find_mid(self, head): slow, fast = head, head while fast and fast.next: # Slow goes one step slow = slow.next # Fast goes two steps fast = fast.next and fast.next.next return slow def reverse(self, head): prev = None node = head while node: tmp = node.next node.next = prev prev = node node = tmp return prev or head
0
0
Comments
Comments
On this page