题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ function deleteDuplicates(head) { // write code here const map = new Map(); let cur = head; let pre; let newList = null; 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; } cur = head; while (cur) { let temp = cur; cur = cur.next; if (map.get(temp.val) === 1) { if (!pre) { pre = temp; newList = pre; pre.next = null } else { pre.next = temp; pre = pre.next; pre.next = null; } } } return newList; } module.exports = { deleteDuplicates: deleteDuplicates, };
解题思路:用map记录重复的值,然后把具有重复值的节点删掉
#删除有序链表中重复的元素-II#