LeetCode 82. 删除排序链表中的重复元素 II

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
posted @ 2020-12-20 17:57  swordspoet  阅读(58)  评论(0)    收藏  举报