/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @return ListNode类
*/
function deleteDuplicates( head ) {
// write code here
let cache = new Set();
let oldcache = new Set();
while(head){
if(oldcache.has(head.val)){
cache.delete(head.val)
}else{
cache.add(head.val);
oldcache.add(head.val)
}
head = head.next;
}
let temp = Array.from(cache);
if(temp.length === 0){
return
}
let nodes = new ListNode(temp[0]);
let onode = nodes
for(let i = 1;i<temp.length;i++){
onode.next = new ListNode(temp[i]);
onode = onode.next
}
return nodes
}
function ListNode(x){
this.val = x;
this.next = null;
}
module.exports = {
deleteDuplicates : deleteDuplicates
};
第二种方法
function deleteDuplicates( head ) {
// write code here
if(!head || !head.next){
return head;
}
let res = new ListNode(-1); // 设置一个伪节点
res.next = head;
let cur = head;
let prev = res;
while(cur && cur.next){ // 如果有一个为null,说明已经到头了,不会再有重复
if(cur.val == cur.next.val){ // 发现重复
while(cur.val == cur.next.val){
cur.next = cur.next.next;
if(!cur.next){// 如果移除到底,则停止
break;
}
}
prev.next = cur.next;
cur = prev.next
}else{
prev = cur;
cur = cur.next
}
}
return res.next;
}