“This is the 9th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Topic:

83. Delete duplicate elements from sorted linked lists

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] 内
  • -100 <= Node.val <= 100
  • The subject data ensures that the linked list is sorted in ascending order

Ideas:

  1. Because the list is already in ascending order, we only need to compare the value of the current element with the value of the next element;
  2. If the value of the current element is equal to the value of the next element, then delete the next element, the operation in the linked list will be directly the next node of the current node, execute the next node;
  3. If the values are not equal, the current pointer is replaced by one element to determine whether the next element coincides until the end;
  4. To return the head pointer to the list, we first need to find someone to run with, leaving the head pointer where it was.

Implementation:

/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
/ * * *@param {ListNode} head
 * @return {ListNode}* /
var deleteDuplicates = function(head) {
    // Find someone to run for you, leaving the head pointer in place
    let cur = head;

    // End condition, there is no next node need not compare
    while (cur && cur.next) {
        // If the values are the same, delete the next node
        if (cur.val === cur.next.val) {
            // Delete the next node
            cur.next = cur.next.next;
        } else {
            // Compare the next element with the one after itcur = cur.next; }}return head;
};
Copy the code

If you understand it, you can click on it and see you in the next topic. If there is no accident after the article will be in this form, there are good suggestions welcome to comment area.