82.删除排序链表中的重复元素


function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var deleteDuplicates = function (head) {
    // 哈希表记录重复次数
    let map = new Map()
    let cur = head
    while (cur) {
        if (map.has(cur.val)) {
            map.set(cur.val, map.get(cur.val) + 1)
        } else {
            map.set(cur.val, 1)
        }
        cur = cur.next
    }

    // 定义一个空头,因为原链表的头可能也是重复的,所以不好在原链表上直接修改
    let prehead = new ListNode()
    cur = prehead
    // 删除元素
    while (head) {
        let count = map.get(head.val)
        // 只留下出现次数为1的元素
        if (count === 1) {
            cur.next = new ListNode(head.val)
            cur = cur.next
        }
        head = head.next
    }

    return prehead.next
};

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var deleteDuplicates = function (head) {
    // 因为原链表头可能是重复的,所以定义一个空头
    let prehead = new ListNode()
    prehead.next = head
    let cur = prehead
    while (cur.next && cur.next.next) {
        // 下一个元素是重复元素
        if (cur.next.val === cur.next.next.val) {
            // 找到重复元素结束的节点
            let val = cur.next.val
            while (cur.next && cur.next.val === val) {
                cur.next = cur.next.next
            }
        } else { // 不是重复元素
            cur = cur.next
        }
    }
    return prehead.next
}