requirements

There is a linked list in ascending order, and you are given the head node of the linked list. Please delete all the nodes in the linked list that have duplicate numbers, and only keep the original list that does not have duplicate numbers.

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

Train of thought

Val == head.next-next-val; val == head.next-next-val

When the two Val’s are not equal, the search continues

When val equals val, cur goes down, pre doesn’t have to move

Until Cur found cur.next. Val! = pre-.next. Val, which causes Pre to change the current pointer to the next node, i.e

code

var deleteDuplicates = function (head) {
    // Return when head is empty
    if(! head)return null;
    // Set a virtual header, because the pre. Next needs to be deleted, when the first and second nodes of the head need to be deleted repeatedly
    let ret = new ListNode(-1, head),
    // The pre points to the virtual head and can be deleted only when the first and second nodes overlap
        pre = ret,
        cur = head;
    // Why is cur&&cur.next not empty?
    // Because cur.next is repeated with previous nodes only when cur and cur.next are not empty
    while (cur && cur.next) {
        // When two nodes do not repeat, each step goes down
        if(pre.next.val ! = cur.next.val) { pre = pre.next; cur = cur.next;/ / repeat
        } else {
            // cur continues down until it finds a node that does not duplicate the current pre-. val
            while (cur.next && pre.next.val == cur.next.val) {
                cur = cur.next;
            }
            // Then pre.next = cur.next, change the direction of the next node of pre
            pre.next = cur.next;
            // cur pointer changes pointcur = cur.next; }}return ret.next;
};
Copy the code