Remove Duplicates from Sorted List

发布时间 2023-06-21 12:17:18作者: Artwalker

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Example 1:

Input: head = [1,1,2]
Output: [1,2]

Example 2:

Input: head = [1,1,2,3,3]
Output: [1,2,3]

Solution:

class Solution(object):
    def deleteDuplicates(self, head):
        if not head:
            return head

        cur = head # 指针,用来串联不重复的元素
        while cur.next:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next

        return head