Description
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Example 1:
Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]
Example 2:
Input: head = [1,1,1,2,3]
Output: [2,3]
Constraints:
The number of nodes in the list is in the range [0, 300].
-100 <= Node.val <= 100
The list is guaranteed to be sorted in ascending order.
Solution
Use a prev
to record the previous node, and if the current node is duplicated by the next node, delete them. Otherwise move prev
forward.
Time complexity:
o
(
n
)
o(n)
o(n)
Space complexity:
o
(
1
)
o(1)
o(1)
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
ret_head = ListNode(-1)
ret_head.next = head
prev, p = ret_head, ret_head.next
while p and p.next:
pn = p.next
need_delete = False
while pn and pn.val == p.val:
need_delete = True
pn = pn.next
if need_delete:
prev.next = pn
p = prev.next
else:
prev, p = prev.next, p.next
return ret_head.next