Look a hundred times beauty, beauty is not necessarily yours. But if you run the algorithm a hundred times, the knowledge is yours

Who can have nine floors? No need to get up!

Title address

The title

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.

Example 1:

Input: head = [1,2,3,3,4,4,5]Copy the code

Example 2:

Input: head = [1,1,1,2,3]Copy the code

Tip:

  • The number of nodes in the linked list is in the range[0, 300] 内
  • -100 <= Node.val <= 100
  • The subject data ensures that the linked list is sorted in ascending order

Their thinking

  • Let’s find the first node with the repeating element
  • Find the first non-repeating node backwards from the node that has repeating elements
  • The leading node of the first element of a node with duplicate elements points to the first non-duplicate node

The problem solving code

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

If you have any questions or suggestions, please leave a comment!