def deleteDuplicates(self, head): cur = head while cur: while cur.next and cur.next.val == cur.val: cur.next = cur.next.next # skip duplicated node cur = cur.next # not duplicate of current node, move to next node return head
def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ cur = head while cur and cur.next: if cur.val == cur.next.val: cur.next = cur.next.next else: cur = cur.next return head
This only takes 56 ms, beats 75%
def deleteDuplicates(self, head): orig = head prev = head head = None if head is None else head.next while head: if prev.val == head.val: prev.next = head.next else: prev = prev.next head = head.next return orig
We don't need to judge whether
cur is None in every step (
while cur.next is enough). My solution is this:
def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None: return head curr = head while curr.next: if curr.next.val == curr.val: curr.next = curr.next.next else: curr = curr.next return head
hey guys, i saw your code in three line"while cur:"
i know that i should check whether cur is none but i don't know why mine
def deleteDuplicates(self, head):
:type head: ListNode
it will mention me "Line 14: AttributeError: 'NoneType' object has no attribute 'next'"(line 14 is:fence=head.next)
can't fence just be None?
I think the reason is None is not a ListNode, thus it doesn't have attribute "next"
@leonick When the input is an empty list '', 'head' will be 'None'. So 'head' will not have the attribute 'next'. That is the error occurred.
But when there is an empty head node in the front of the linked list, your code, I think, is right.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.