Skip to content

Instantly share code, notes, and snippets.

@daifu
Created May 7, 2013 08:27
Show Gist options
  • Save daifu/5531089 to your computer and use it in GitHub Desktop.
Save daifu/5531089 to your computer and use it in GitHub Desktop.
Remove Duplicates from Sorted List II
/*
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if(head == null) return null;
HashMap<Integer, Integer> set = new HashMap<Integer, Integer>();
set.put(head.val, 1);
ListNode cur = head.next;
while(cur != null) {
if(set.containsKey(cur.val)) {
set.put(cur.val, set.get(cur.val) + 1);
} else {
set.put(cur.val, 1);
}
cur = cur.next;
}
cur = head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode prev = dummy;
while(cur != null) {
if(set.get(cur.val) > 1) {
prev.next = cur.next;
cur = cur.next;
} else {
prev = cur;
cur = cur.next;
}
}
return dummy.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment