You’re 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.
Given the following linked list: 1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5
, return 1 -> 2 -> 5
.
Given the following linked list: 1 -> 1 -> 1 -> 2 -> 3
, return 2 -> 3
.
Initialize a dummy node: Create a dummy node to simplify edge cases and use it to build the resulting list.
Iterate through the list: Use a pointer (current
) to traverse the linked list.
Skip duplicates: While traversing, check if the current node has the same value as the next node. If so, skip all nodes with this value.
Add non-duplicates to the result list: If the next value is not a duplicate, attach it to the result list.
Move to the next unique value: Continue this process until the end of the linked list.
Here is the Python code to solve this problem:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def deleteDuplicates(head: ListNode) -> ListNode:
# Create a dummy node to handle edge cases
dummy = ListNode(0)
dummy.next = head
current = dummy
while current.next and current.next.next:
if current.next.val == current.next.next.val:
# Detected duplicates, get the duplicate value
dup_val = current.next.val
# Skip all nodes with this duplicate value
while current.next and current.next.val == dup_val:
current.next = current.next.next
else:
# No duplicate detected, move to the next node
current = current.next
return dummy.next
This approach efficiently removes all duplicates from the sorted linked list and maintains the required sorted order.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?