算法笔记2:删除排序链表中的重复元素

129 阅读1分钟

82. 删除排序链表中的重复元素

递归解法可以很简单的解决这道题。思路就是对每一个元素后面的整个链表进行从头开始的去重即可,这样遍历完整条链表之后,就没有重复的元素了。

const deleteDuplicates = head => {
  // for the last item, return itself
  if (!head || !head.next) {
    return head;
  }
  
  // check if there are repeated items
  if (head.next.val === head.val) {
    const p = head.next;
    while(p && p.val === head.val) {
      p = p.next;
    }
    
    // continue the recursion, always return an item
    return deleteDuplicates(p);
  }
  
  // if the code flows to here,
  // then the curr item's value is different than next item's.
  // so change the pointer to the return value of the recursion
  head.next = deleteDuplicates(head.next);
  // and return self
  return head;
}