Remove Duplicates from Sorted List:
Given the head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Input: head = [1,1,2]
Output: [1,2]
Input: head = [1,1,2,3,3]
Output: [1,2,3]
[0, 300]
.-100 <= Node.val <= 100
Try this Problem on your own or check similar problems:
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return null;
ListNode dummy = new ListNode(-1, head), curr = dummy.next;
while(curr != null){
while(curr.next != null && curr.val == curr.next.val){
curr.next = curr.next.next;
}
curr = curr.next;
}
return dummy.next;
}
The problem is really similar to the
Remove Linked List Elements
where we have a sentinel node and we iterate through list and for each node check if it’s next node has the same value, if it has we relink the current node to point to the next node and repeat the process until we find a node with a value that’s different than the value at current node. Dummy node will be pointing to the new head so we just have to return dummy.next
.
Don’t settle for anything less than the crown. Join our newsletter and become the King of Interviews! Click here to join now and get the latest updates.