import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode deleteDuplicates (ListNode head) {
        if(head==null||head.next==null){
                return head;
            }
            HashMap<Integer,ListNode> hm=new HashMap<>();
            ListNode h=new ListNode(-1);
            h.next=head;
            ListNode cur=head;
            ListNode pre=h;
            while (cur!=null){
                if(hm.containsKey(cur.val)){
                    pre.next=cur.next;
                    hm.get(cur.val).val=Integer.MAX_VALUE;
                }else {
                    hm.put(cur.val,cur);
                    pre=cur;
                }
                cur=cur.next;
            }
            pre=h;
            cur=h.next;
            while (cur!=null){
                if(cur.val==Integer.MAX_VALUE){
                    pre.next=cur.next;
                }else {
                    pre=cur;
                }
                cur=cur.next;
            }
            return h.next;
    }
}

解题思路:第一次循环删除重复且非第一次出现的元素并标记重复且第一次出现的元素,第二次删除被标记的元素