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) {
        // write code here
        if (head == null) return null;
        List<ListNode> nodeList = new ArrayList<>();
        nodeList.add(head);
        ListNode temp = head;
        while (true) {
            ListNode next = temp.next;
            if (next == null) break;
            nodeList.add(next);
            temp = next;
        }

        Map<Integer, ListNode> nodeMap = new LinkedHashMap<>();
        Set<Integer> intSet = new HashSet<>();
        int loopNum = nodeList.size();
        for (int i = 0; i < loopNum; i++) {
            ListNode target = nodeList.get(i);
            int tempVal = target.val;
            if (nodeMap.containsKey(tempVal)) {
                nodeMap.remove(tempVal);
            } else {
                if (!intSet.contains(tempVal)) {
                    nodeMap.put(tempVal, target);
                    intSet.add(tempVal);
                }
            }
        }

        ListNode realNode = null;
        ListNode currentNode = null;
        for (Map.Entry<Integer, ListNode> entry : nodeMap.entrySet()) {
            if (realNode == null) {
                realNode = entry.getValue();
                realNode.next = null;
                currentNode = realNode;
            } else {
                currentNode.next = entry.getValue();
                if(currentNode.next.next != null){
                    currentNode.next.next = null;
                }
                currentNode = currentNode.next;
            }
        }

        return realNode;
    }
}