Given a sorted linked list, delete all duplicates such that each element appear only once.
Constraints
Approach
Links
GeeksforGeeks
YouTube
Examples
Input: 1 -> 1 -> 2
Output: 1 -> 2
Input: 1 -> 1 -> 2 -> 3 -> 3
Output: 1 -> 2 -> 3
Solutions
/**
* Time complexity : O(n). Because each node in the list is checked exactly
* once to determine if it is a duplicate or not, the total run time
* is O(n), where n is the number of nodes in the list.
* Space complexity : O(1). No additional space is used.
*/
/**
* Definition for singly-linked list.
* public 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) {
if(head == null) return null;
ListNode curr = head;
while(curr.next != null) {
if(curr.val == curr.next.val) {
curr.next = curr.next.next;
} else {
curr = curr.next;
}
}
return head;
}
}