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

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,3,3,4,4,5]Copy the code

LeetCode link: leetcode-cn.com/problems/re…

Their thinking

  1. This is similar to 83 deleting the duplicate elements from a sorted list, except that one of the duplicate elements is retained. In this problem, all duplicate elements are removed
  2. A linked list is an ordered linked list. The same nodes are continuous
  3. Create a false head node, next points to head, and the repetition of head nodes becomes normal
  4. Iterate through the linked list and delete the current node in either of the following ways:
    • The value of the current node equals the value of the next node
    • The value of the current node is equal to the value of the last node removed
  5. Handle boundary conditions, return head if head is empty

Example 2:

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

Code implementation

var deleteDuplicates = function(head) { if (! head) return head let weakHead = new ListNode(null, Head) let curr = weakHead let prev = weakHead let delNode = null while (curr) {// Two cases delete the current node: //1. The value of the current node value is equal to the next node / / 2. The value of the current node value is equal to the last node is removed the if ((curr. Next && curr. Val = = = curr. Next. Val) | | (delNode && curr. Val = = = delNode.val)) { delNode = curr prev.next = curr.next curr = curr.next } else { prev = curr curr = curr.next } } return weakHead.next }Copy the code

If there are mistakes welcome to point out, welcome to discuss together!