题解 | 删除有序链表中重复的元素-I
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* {1,1,2} => {1,2}
* {} => {}
*
* @param head ListNode类
* @return ListNode类
*/
function deleteDuplicates(head) {
// write code here
let arr = []; // 利用一个数组存储出现的元素
let resHead = new ListNode();
let res = resHead;
while (head) {
if (!arr.includes(head.val)) {
arr.push(head.val);
res.next = head;
res = res.next;
} else {
res.next = null; // 需要处理 {1,1} 的情况,断开原有的链表
}
head = head.next;
}
return resHead.next;
}
module.exports = {
deleteDuplicates: deleteDuplicates,
};

