Reputation:
I have written some code below to determine is a Linked List is a palindrome, but when I run it through tests cases it simply times out. Any idea what is wrong with the code? Thanks
def isPalindrome(self, head: ListNode) -> bool:
if head == None:
return True
length_ll = 0
curr = head
while curr:
length_ll +=1
curr = curr.next
mid_point = length_ll//2
head2 = head
for _ in range(mid_point):
head2 = head2.next
prev = head2
curr = head2
nex = head2.next
while nex:
curr = nex
curr.next = prev
nex = nex.next
prev = curr
head2.next = None
curr = head
curr2 = head2
while curr or curr2:
if curr2.val != curr.val:
return False
else:
curr = curr.next
curr2 = curr2.next
return True
Upvotes: 0
Views: 26
Reputation: 146
Your 3rd while
statement is infinite (if curr2.val == curr.val
it will never stop)
Upvotes: 1