LeetCode - 82. Remove Duplicates from Sorted List II | Lacerta

82. Remove Duplicates from Sorted List II

BF

实现

保存链表至数组,操作数组,拼成链表

提示I - One Pass

实现

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var deleteDuplicates = function (head) {
  const dummy = new ListNode(0);
  dummy.next = head;
  
  let fast = head;
  let slow = dummy;

  while (fast !== null) {
    if (fast.next === null || fast.next.val !== fast.val) {
      if (slow.next === fast) {
        slow = fast;
      } else {
        slow.next = fast.next;
      }
    }

    fast = fast.next;
  }

  return dummy.next;
};