Delete duplicate node 2 from sort linked list

Give you a sorted duplicate linked list and remove all duplicate nodes.

The problem solving code

Ideas:

  1. Define a virtual head and determine if the list head node starts with a duplicate node.
  2. If there are repetitions to continue, find the next different node and move the virtual head pointer to the current node.
  3. If not, the current pointer takes a step back and repeats until the list is empty.
var deleteDuplicates = function(head) {
  if(! head)return null;
  let ret = new ListNode(-1,head); / / empty head
  let p = ret;
  let q;
  while (p.next) {
    if(p.next.next && p.next.val === p.next.next.val){ // Check whether there is a repeat at the next node of p
      q = p.next.next; // If there is duplication, then assign the current next node to q
      while (q && q.val === p.next.val) q = q.next; // If the value of q is equal to the value of the repeated nodes, then q continues to go back until different nodes are found
      p.next = q; // At this point q has reached the position of the different nodes, joins them together, and continues the loop until the list is empty
    }else {
      p = p.next; // If there is no repetition, p takes a step back}}return ret.next; // The new list header after processing.
};
Copy the code