leetcode 82. remove duplicates from sorted list ii

82. Remove Duplicates from Sorted List II

Difficulty: Medium

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

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

Solution

Language: Java

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
31
32

* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
int cur = 0;
while(head != null) {
if (head.next != null && head.val == head.next.val) {
cur = head.val;
while (head != null && head.val == cur) {
head = head.next;
}
prev.next = head;
} else {
prev = head;
head = head.next;
}
}
return dummy.next;
}
}