js_algorithm
js_algorithm copied to clipboard
删除排序链表中的重复元素 II
leetcode: https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/
题目分析
和这道题类似,也是删除重复元素,不同的是本道题目在删除后不允许有重复的元素留在链表中。
要删除某一个目标结点时,必须知道它的前驱结点
。
但现在的问题是可能存在多个相同的元素连在一起,如果删除,就会连带删除它的前驱节点
和后继节点
。
遇到这种情况,我们一般需要通过dummy
节点来解决。
所谓
dummy
结点,就是咱们人为制造出来的第一个结点的前驱结点
,这样链表中所有的结点都能确保有一个前驱结点,也就都能够用同样的逻辑来处理了。
编码实现
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
if(!head || !head.next) {
return head;
}
let dummy = new ListNode();
dummy.next = head;
let cur = dummy;
while(cur.next && cur.next.next) {
if(cur.next.val === cur.next.next.val) {
let val = cur.next.val;
while(cur.next && cur.next.val === val) {
cur.next = cur.next.next;
}
} else {
cur = cur.next
}
}
return dummy.next
};