注意:
1.设置伪结点,方便处理
3.当遇到当前节点值和下一节点值相等的节点时,进行while循环找到下一个不相等的节点,挂到prev节点上
4.当遇到当前节点值和下一节点值不相等的节点时,prev和curr都移动到下一个节点接着遍历就行
function deleteDuplicates( head ) {
if(head==null || head.next==null)
return head;
let dummy = new ListNode(-9999);
dummy.next = head;
let pre = dummy;
let cur = head;
while(cur!=null && cur.next!=null){
if(cur.val == cur.next.val){
let temp = cur.next;
while(temp!=null && temp.val == cur.val)
temp = temp.next;
pre.next = temp;
cur = temp;
}else{
pre = pre.next;
cur = cur.next;
}
}
return dummy.next;
}
module.exports = {
deleteDuplicates : deleteDuplicates
};
另一种
function deleteDuplicates( head ) {
if(head==null || head.next==null) return head;
let empty = new ListNode(-100),
pre = empty;
while(head){
let flag = false;
let val = head.val;
let temp = head.next;
while(temp && temp.val == val){
flag = true;
temp = temp.next;
}
if(flag==false){
pre.next = head;
head = head.next;
pre = pre.next;
}else{
head = temp;
}
}
pre.next = null;
return empty.next;
}