I tried the method where you go through the head, compare it to the curr of the new ListNode I made. If it doesn't exist already, add it. However, it looks like it doesn't work properly for duplicates so I switched the strategy to copying over the entire head into the new ListNode and updating curr.next if it equals curr's value to curr.next.next which worked. However, I still want to figure out why my previous method/strategy didn't work and how I can fix it. Previous strategy I couldn't get to work:
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
temp = ListNode()
curr = temp
while head:
if head.val != curr.val:
curr.next = head
head = head.next
curr = curr.next
else:
head = head.next
return temp.next
Example where it fails:
head = \[1,1,2,3,3\]
My output
\[1,2,3,3\]
Expected
\[1,2,3\]
It only goes into my if statement the 3 times because when I have a print statement under curr = curr.next, it just prints 1,2,3. However when it prints the final product it somehow gets another 3.
To fix this I added curr.next = None before temp.next but this won't work when head = [0,0,0]