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

题目

存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现 的数字。

返回同样按升序排列的结果链表。

示例 1:
输入:head = [1,2,3,3,4,4,5]
输出:[1,2,5]

示例 2:
输入:head = [1,1,1,2,3]
输出:[2,3]

提示:

  • 链表中节点数目在范围 [0, 300] 内
  • -100 <= Node.val <= 100
  • 题目数据保证链表已经按升序排列

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

JS实现

/**
 * 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) {
  //设置哑节点,方便删除
  let dummy = new ListNode(0);
  dummy.next = head;

  let current = dummy;
  while (current.next != null && current.next.next != null) {
    // 如果当前节点的下个节点 与当前节点下下个节点 的值 相等
    if (current.next.val === current.next.next.val) {
      let temp = current.next;
      // 如果后续节点的值还是相等,再继续右移
      while (temp != null && temp.next != null && temp.val === temp.next.val) {
        temp = temp.next;
      }
      current.next = temp.next;
    } else {
      // 不相等,current右移
      current = current.next;
    }
  }
  return dummy.next;
};