[Leetcode]82. Remove Duplicates from Sorted List II

Question

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

For example,

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

Solution

Because the head of linked list could be duplicated, so we need to add a dummy head node to the original linked list. Then check the values of node, if it’s duplicated just skip the node and redirect the pointer to next node.

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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/

public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if( head == null || head.next == null ){ //edge case
return head;
}
ListNode ret = new ListNode(0); // fake head
ret.next = head;
head = ret;
while(head.next != null && head.next.next != null){ // start checking
if(head.next.val == head.next.next.val){
int value = head.next.val;
while( head.next != null && head.next.val == value ){
head.next = head.next.next; //redirect head's next pointer
}
}else{
head = head.next; //head move to next node
}
}

return ret.next;

}
}
写得好!朕重重有赏!