Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
Set<Integer> set = new HashSet<Integer>();
ListNode tmp = head;
ListNode tmp2 = null;
if(head != null) {
set.add(head.val);
tmp2 = head.next;
}
while(tmp2 != null) {
if (set.contains(tmp2.val)) {
ListNode p = tmp2.next;
tmp.next = p;
tmp2 = tmp.next;
} else {
set.add(tmp2.val);
tmp = tmp2;
tmp2 = tmp2.next;
}
}
return head;
}
}