[leetcode] 82. Remove Duplicates from Sorted List II

题目

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

Example 1:

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

Example 2:

Input: head = [1,1,1,2,3]
Output: [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.

思路

快慢指针,快指针遍历链表的同时,慢指针停留在最近非重复数值的位置,当快慢指针之间出现多个重复数值时,则切断快慢指针之间多余的节点。

代码

python版本:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head:
            return
        pre_root = ListNode(0, head)
        slow = pre_root
        now = head
        count = 0
        val = head.val
        while now != None:
            if now.val == val:
                count += 1
            elif count >= 2:
                val = now.val
                slow.next = now
                count = 1
            else:
                val = now.val
                slow = slow.next
                count = 1
            now = now.next
        if count >= 2:
            slow.next = now
        return pre_root.next
posted @ 2022-03-15 14:40  frankming  阅读(22)  评论(0编辑  收藏  举报