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

Answer:

  1. The list is traversed with a double pointer, prev pointing to the current node, and Set holding the value of the current node.
  2. If a duplicate element is encountered during traversal, point the prev node to the curr.next node to delete the current node.
/ * * *@param {ListNode} head
 * @return {ListNode}* /
var deleteDuplicates = function (head) {
  let set = new Set(a);// Use Set to save the value of the traversed node
  // Create a prev node that points to the node being traversed and can be used to delete the current node when a duplicate node occurs
  let prev = new ListNode(null);
  prev.next = head; // The prev node points to the header before the traversal begins
  let curr = head; // Used to traverse the list

  // Iterate over the list
  while (curr) {
    // If the value of the node is already saved, delete the current node
    if (set.has(curr.val)) {
      // Delete the current node by pointing the prev node directly to the next node
      prev.next = curr.next;
      // The current node moves forward one bit
      curr = curr.next;
    } else {
      // Save the value of the current node
      set.add(curr.val);
      // Both the prev node and the current node move forward one bit to continue traversing the listprev = curr; curr = curr.next; }}// return the head node to return the new list
  return head;
};
Copy the code