函式遞迴與二分法
阿新 • • 發佈:2020-12-20
82. 刪除排序連結串列中的重複元素 II
Difficulty: 中等
給定一個排序連結串列,刪除所有含有重複數字的節點,只保留原始連結串列中_沒有重複出現_的數字。
示例1:
輸入: 1->2->3->3->4->4->5
輸出: 1->2->5
示例2:
輸入: 1->1->1->2->3
輸出: 2->3
Solution
# 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 not head: return None res = ListNode(-1) res.next = head pre = res while head and head.next: if head.val == head.next.val: while head and head.next and head.val == head.next.val: head = head.next head = head.next pre.next = head else: pre = pre.next head = head.next return res.next