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]

Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

Solution in python:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if head == None:
            return None
        first = ListNode(head.val)
        pre = first
        while head != None:
            if pre.val == head.val:
                pre.next = head.next
                head = head.next
            else:
                pre = head
                head = head.next
        return first
最后修改日期: 2021年1月5日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。