leeCode算法--删除链表中的重复项

题目:存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。返回同样按升序排列的结果链表。

分析:升序链表,那么重复项一定就是相邻项,所以只需要判断相邻项是否相等,如果相等则就指向下一项即。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function ListNode (val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? : null : next)
}
let deleteDuplicates = head => {
if (!head) return head
let current = head
while (current.next) {
if (current.val === current.next.val) {
current.next = current.next.next
} else {
current = current.next
}
}
return head
}

That’s all!

  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2022 Lee
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信