Skip to content

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

题目

给定一个已排序的链表的头 head删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表

示例 1:

img

输入:head = [1,1,2]
输出:[1,2]

示例 2:

img

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

提示:

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

解答

思路

保留头节点就不需要 dummy。算法:只要 cur.next.val == cur.val,就删除 cur.next,如此直到 cur.next = None 为止。

  • 时间复杂度为 O(n)
  • 空间复杂度为 O(1)

代码

Python 代码

python
class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head is None:
            return head
        
        cur = head
        while cur.next:
            if cur.next.val == cur.val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        
        return head

Released under the MIT License.