Skip to content

力扣链接:83.删除排序链表中的重复元素

难度:⭐

解题关键词:链表

解题思路:使用一个指针,从前往后遍历,遇到重复的,直接把重复的节点跳过。

typescript
function deleteDuplicates(head: ListNode | null): ListNode | null {
  if (!head) return head;

  let cur = head;
  while (cur.next) {
    // 和下一个节点值一样,把 next 指向再后面一个
    if (cur.val === cur.next.val) {
      cur.next = cur.next.next;
    } else {
      // 不相等,往后移动
      cur = cur.next;
    }
  }

  return head;
}