LeetCode - Remove Duplicates from Sorted List II

less than 1 minute read

Problem description

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.

Example 1:

1
2
Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

1
2
Input: 1->1->1->2->3
Output: 2->3

Analysis

General idea is to use a if statement to check if contains duplicate, if so then skip all duplicates, if not then add the next item into the result;

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
public ListNode deleteDuplicates(ListNode head) {
        if (head == null){
            return head;
        }
        ListNode dummy = new ListNode(head.val - 1);
        ListNode p = dummy;
        
        dummy.next = head;
        
        while (p.next != null){
            int v = p.next.val;
            if (p.next.next != null && p.next.next.val == v){
                ListNode l = p.next;
                while (l != null && l.val == v){
                    l = l.next;
                }
                
                p.next = l;
            }
            else{
                p = p.next;                
            }
        }
        
        return dummy.next;
    }

What to improve

  • null checking for linked list questions.

valid-sudoku