Simple iterative Python 6 lines, 60 ms


  • 13
    Z
    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

  • 3
    D
    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

  • 0
    R

    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      
    

  • 0
    H

    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
    

  • 0
    L

    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
    '''
    class Solution(object):
    def deleteDuplicates(self, head):
    """
    :type head: ListNode
    :rtype: ListNode
    """
    last=head
    fence=head.next
    while fence.next:
    if fence.next.val==last.val:
    last.next=fence.next
    del fence
    fence=last
    return head
    '''
    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?


  • 0
    A

    @leonick
    I think the reason is None is not a ListNode, thus it doesn't have attribute "next"


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.