wondering if I can get some help on this. Suppose you are trying to determine if a linked list is palindromic using something like this:
def isPalindrome(self, head: ListNode) -> bool:
current, prev = head, None
if not head:
return False
if not head.next:
return True
while current:
nextnode = current.next
current.next = prev
prev = current
current = nextnode
print(current, prev)
if current:
if current == prev or current.next == prev:
return True
return False
Where a ListNode is defined as:
class ListNode():
def __init__(self, val=None, next=None):
self.val = val
self.next = next
The thought here is begin restructuring for a reverse list and check for node equality (or next node equality for an even number of nodes) at each step. Running this code on a sample LL that points 1 -> 2 -> 2 -> 1 returns false but if we check objects that are being compared:
ListNode{val: 2, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}} ListNode{val: 1, next: None}
ListNode{val: 2, next: ListNode{val: 1, next: None}} ListNode{val: 2, next: ListNode{val: 1, next: None}}
ListNode{val: 1, next: None} ListNode{val: 2, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}
None ListNode{val: 1, next: ListNode{val: 2, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}
You can see in the output from the print that there is a case where the nodes appear to return identically structured lists (line 2). I assume that the comparison is failing because the starting point of either of the split lists, although a 2 -> 1, is a different 2 -> 1 in memory and thus the comparison fails?
If my understanding of why this fails is correct, is there a way to compare the nodes to make this work (without going outside of O(n) runtime)?
P.S. I don't want a different solution, I was just curious if there is a way to make this work :)