menu

[LeetCode] 082. Remove Duplicates from Sorted List II *

Problem (Medium)

082. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

  • Input: 1->2->3->3->4->4->5
  • Output: 1->2->5

Example 2:

  • Input: 1->1->1->2->3
  • Output: 2->3

Approach 1: Top Solution from LeetCode Discussion - Dummy Head!!!

Idea

Accepted Java code from snowfish

Solution

class Solution1:
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return
        fakeHead = ListNode(0)
        fakeHead.next = head
        pre = fakeHead
        cur = head
        while cur:
            while cur.next and cur.val == cur.next.val:
                cur = cur.next
            if pre.next == cur:
                pre = pre.next
            else:
                pre.next = cur.next
            cur = cur.next
        return fakeHead.next

Complexity

  • Time: $O(n)$
  • Space: $O()$



KF

Comments