83. Remove Duplicates from Sorted List

Description

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3.

Solution

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * Solved with two pointers
 * @param {ListNode} head
 * @return {ListNode}
 */
var deleteDuplicates = function(head) {
    "use strict";
    if (!head) {
        return head;
    }
    let ptr1 = head, ptr2 = head;
    while (ptr1) {
        if (ptr1.val !== ptr2.val) {
            if (ptr2.next !== ptr1) {
                ptr2.next = ptr1;
            }
            ptr2 = ptr1;
        }
        ptr1 = ptr1.next;
    }
    ptr2.next = null;
    return head
};

results matching ""

    No results matching ""