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.
For example:
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:
[0, 300]
.-100 <= Node.val <= 100
A brute force solution to this problem would involve iterating through the linked list, keeping track of the frequency of each value, and then constructing a new linked list containing only the distinct values. This approach would require extra space to store the frequencies.
An optimal solution can be achieved by iterating through the linked list and removing the duplicate nodes in place. This approach requires only constant extra space.
prev
and curr
, to the dummy node and the head of the list, respectively.curr.next != null && curr.val == curr.next.val
):
prev.next
to point to the node after the duplicates.prev
to curr
.curr
to curr.next
.class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(0, head);
ListNode prev = dummy;
ListNode curr = head;
while (curr != null) {
if (curr.next != null && curr.val == curr.next.val) {
while (curr.next != null && curr.val == curr.next.val) {
curr = curr.next;
}
prev.next = curr.next;
} else {
prev = curr;
}
curr = curr.next;
}
return dummy.next;
}
}