1
+ # Given the head of a sorted linked list, delete all nodes that have duplicate
2
+ # numbers, leaving only distinct numbers from the original list. Return the
3
+ # linked list sorted as well.
4
+
5
+
6
+ # Example 1:
7
+ # Input: head = [1,2,3,3,4,4,5]
8
+ # Output: [1,2,5]
9
+
10
+ # Example 2:
11
+ # Input: head = [1,1,1,2,3]
12
+ # Output: [2,3]
13
+
14
+
15
+ # Constraints:
16
+
17
+ # The number of nodes in the list is in the range [0, 300].
18
+ # -100 <= Node.val <= 100
19
+ # The list is guaranteed to be sorted in ascending order.
20
+
21
+
22
+
23
+ from typing import Optional
24
+ # Definition for singly-linked list.
25
+ class ListNode :
26
+ def __init__ (self , val = 0 , next = None ):
27
+ self .val = val
28
+ self .next = next
29
+ class Solution :
30
+ def deleteDuplicates (self , head : Optional [ListNode ]) -> Optional [ListNode ]:
31
+ dummy = ListNode (0 , head )
32
+ current = head
33
+ prev = dummy
34
+ while current :
35
+ while current .next and current .val == current .next .val :
36
+ current = current .next
37
+ if prev .next == current :
38
+ prev = prev .next
39
+ else :
40
+ prev .next = current .next
41
+ current = current .next
42
+ return dummy .next
43
+
0 commit comments