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. Given the head node of the linked list, remove all duplicate elements so that each element appears only once.

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

Example 1:

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

Example 2:

Head = [1,1,2,3,3]Copy the code

Tip:

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

Their thinking

  • Because lists are ordered, repeating elements must be connected
  • We just need to compare the values of the two adjacent nodes
  • If they are equal, the left node points to the right node after the node is deleted

The problem solving code

var deleteDuplicates = function(head) {
    if(! head)return head
    let cur = head
    while(cur.next){
        if(cur.val == cur.next.val){
            cur.next = cur.next.next
        }else{
            cur = cur.next
        }
    }
    return head
};
Copy the code

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