menu

[LeetCode] 083. Remove Duplicates from Sorted List

Problem (Easy)

083. Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

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

Example 2:

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

Approach 1: (My Solution)

Idea

Solution

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

Complexity

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



KF

Comments