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) {
if(head == null) return head;
Set<Integer> set = new HashSet<Integer>();
set.add(head.val);
ListNode node = head;
while(node.next != null){
if(set.contains(node.next.val)){
node.next = node.next.next;
}else{
set.add(node.next.val);
node = node.next;
}
}
return head;
}
}