Ray-56 / like-algorithms

每天一道算法题,突破自己
2 stars 1 forks source link

✅82. 删除排序链表中的重复元素 II #134

Open Ray-56 opened 4 years ago

Ray-56 commented 4 years ago

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

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。

示例 1:

输入: 1->2->3->3->4->4->5
输出: 1->2->5

示例 2:

输入: 1->1->1->2->3
输出: 2->3
Ray-56 commented 4 years ago
var deleteDuplicates = function(head) {
    if (!head) return head;

    const newHead = new ListNode();
    newHead.next = head;
    let fast = head;
    let slow = newHead;

    while (fast && fast.next) {
        if (fast.val === fast.next.val) {
            const value = fast.val;
            while (fast && value === fast.val) {
                fast = fast.next;
            }
            slow.next = fast;
        } else {
            fast = fast.next;
            slow = slow.next;
        }
    }
    return newHead.next;
};