Skip to main content

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

给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。

示例 1:

输入:head = [1,1,2]
输出:[1,2]

示例 2:

输入:head = [1,1,2,3,3]
输出:[1,2,3]

答案

const head = {
'val':1,
'next':{
'val':2,
'next':{
'val':2,
'next':undefined
}
}
}

思路:

  1. 防御性
  2. 当前节点与下节点的 val 对比
    • 相同:cur.next = cur.next.next
    • 不相同:cur = cur.next
var deleteDuplicates = function(head) {
if (!head) { return head }

let cur = head;
while (cur.next) {
if (cur.val === cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
};
deleteDuplicates(head)