Home [Medium] Remove Duplicates from Sorted List II
Post
Cancel

[Medium] Remove Duplicates from Sorted List II

‘Remove Duplicates from Sorted List II (Medium)’


📌 Problem

https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

📌 Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        // sentinel
        ListNode sentinel = new ListNode(0, head);

        // predecessor = the last node 
        // before the sublist of duplicates
        ListNode pred = sentinel;
        
        while (head != null) {
            // if it's a beginning of duplicates sublist 
            // skip all duplicates
            if (head.next != null && head.val == head.next.val) {
                // move till the end of duplicates sublist
                while (head.next != null && head.val == head.next.val) {
                    head = head.next;    
                }
                // skip all duplicates
                pred.next = head.next;     
            // otherwise, move predecessor
            } else {
                pred = pred.next;    
            }
                
            // move forward
            head = head.next;    
        }  
        return sentinel.next;
    }
}
This post is licensed under CC BY 4.0 by the author.

[Easy] Convert Binary Number in a Linked List to Integer

[Medium] Swap Nodes in Pairs

Comments powered by Disqus.