Python solution with detailed explanation


  • 0
    G

    Solution

    Remove Duplicates from Sorted List https://leetcode.com/problems/remove-duplicates-from-sorted-list/?tab=Description

    Algorithm

    • Use a sentinel node and a variable prev to track same numbers.
    class Solution(object):
        def deleteDuplicates(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            result = ListNode(-1)
            curr, prev = result, None
            while head:
                if prev == None or head.val != prev:
                    prev = head.val
                    curr.next = head
                    curr = head
                    head = head.next
                    curr.next = None
                else:
                    head = head.next                
            return result.next
    

Log in to reply
 

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