Remove Duplicates from Sorted List II

Jesus PF
2 min readJan 10, 2021

From the leetcode exercise https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/579/week-1-january-1st-january-7th/3593/

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.

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:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

Solution

/**
* 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) {
ListNode prev=new ListNode(-101,head);
ListNode result = prev;

//iterate from begining to end
//find repeated else go on
//if found get next node after repeated
//skip repeated

while( head != null){
if(head.next != null && head.val == head.next.val ){
int value=head.val; //1
while(head != null && value == head.val){
head=head.next;
}
prev.next = head;
}else{
prev = head;
head=head.next;
}
}
return result.next;
}
}

--

--

Jesus PF

I am en electronics engineer, graduated from ITESM. Experienced working as functional validation and software development.