requirements

There is a list in ascending order. Pass in the head node of the list, head, and remove all duplicate elements so that each element appears only once.

Returns a linked list of results, also in ascending order.

Idea 1

Create a Pre pointing to head

Create a cur pointing to head.next

When the pre. Val = = cur. Val

pre.next = cur.next

The pre to cur

Cur to cur. Next

var deleteDuplicates = function (head) {
    if(! head)return null;
    let ret = new ListNode(-1, head),
        pre = head,
        cur = head.next;
    while (cur) {
        if (pre.val === cur.val) {
            pre.next = cur.next;
            pre = cur.next;
            if(! pre)break;
            cur = pre.next;
        } else{ pre = pre.next; cur = cur.next; }}return ret.next;
};
Copy the code

But in this case, you can only handle duplicate elements that occur only twice

Idea 2

Create a Pre pointing to head

Create a cur pointing to head.next

When the pre val! = cur.val

Pre points to cur, cur to cur.next

When pre-. val == cur.val only does the cur pointer to the next: cur = cur.next operation so that duplicate elements occur more than once can be deleted

code

var deleteDuplicates = function (head) {
    // Return null if head is null
    if(! head)return null;
    // Create two Pointers to head and head. Next to determine if val is equal
    let pre = head,
        cur = head.next;
    // The loop starts when cur is not empty, which means the list has been traversed
    while (cur) {
        // When pre is not equal to cur, the two nodes do not duplicate
        if(pre.val ! = cur.val) {// Next of the node currently pointed to by pre points to cur
            pre.next = cur;
            // The pre pointer points to the node to which the current cur pointer points
            pre = cur;
            // The cur pointer points to the next node to which the current cur pointer points
            cur = cur.next;
        } else {
            // When pre points to a node that has the same value as cur, the two nodes repeat and cur points to the next nodecur = cur.next; }}// After the while loop, if the last pre node is repeated with cur, pre points to null; if not, pre points to the last node
    pre.next = null;
    return head;
};
};
Copy the code