Reputation: 11
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode()
dummy.next = head
while dummy and dummy.next:
if dummy.val == dummy.next.val:
dummy.next = dummy.next.next
else:
dummy = dummy.next
return dummy.next
So I'm doing one of the Leetcode problem call remove duplicate from sorted list, i created a dummy node which it's next is head, however when i try to test it with head = [1,2,3,3,4,4,5], return dummy.next is giving a empty list as output and return head is giving the correct output, i'm wondering why is that since dummy.next should be equal to head?
Upvotes: 1
Views: 125
Reputation: 350310
The idea to use this dummy
is good, but then you shouldn't assign anything else to it. In your loop you should use another name for traversing the list -- not dummy
: this could be a new name like curr
, or you could even use head
for it:
dummy = ListNode()
dummy.next = head
while head and head.next:
if head.val == head.next.val:
head.next = head.next.next
else:
head = head.next
return dummy.next
Upvotes: 3