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.
Example 1:
Input: head = [1,1,2]
Output: [1,2]
Example 2:
Input: head = [1,1,2,3,3]
Output: [1,2,3]
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode current_node = head;
while (current_node!=null && current_node.next != null){
if(current_node.val == current_node.next.val){
current_node.next = current_node.next.next;
} else{
current_node = current_node.next;
}
}
return head;
}
}
Time: O(n) Space: O(1)
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)return head;
head.next = deleteDuplicates(head.next);
return head.val == head.next.val ? head.next : head;
}
}
Time: O(n) Space: O(n)