82. Remove Duplicates from Sorted List II
Description
Given 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.
Constraints
Approach
Links
GeeksforGeeks
YouTube
Examples
Input: 1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5
Output: 1 -> 2 -> 5
Solutions
/**
* Time complexity :
* Space complexity :
*/
/**
* 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 node = new ListNode(-1);
node.next = head;
ListNode curr = node;
while(curr.next != null && curr.next.next != null) {
if(curr.next.val == curr.next.next.val) {
int value = curr.next.val;
while(curr.next != null && curr.next.val == value) {
curr.next = curr.next.next;
}
} else {
curr = curr.next;
}
}
return node.next;
}
}
Follow up
Last updated
Was this helpful?