Leetcode 82. Remove Duplicates from Sorted List II

Description: Given 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.

Link: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

Examples:

Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:
Input: 1->1->1->2->3
Output: 2->3

思路: 和83的区别在于,1) 只要这个元素出现过两次及以上,就删除,所以当前元素不仅要和前面的比较,还要和后面的比较,当与前后都不同时,才被添加到返回链表中,2) pre的更新也不同,83中,当pre和当前值不同时,才更新,相同则不更新,这里要随着指针移动而更新。3) 注意return linked list的head,如果从链表的第二个元素开始遍历,需要先确认第一个元素是否unique.

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head: return head
        if not head.next: return head
        
        rhead = ListNode(0)
        r = rhead
        pre = head.val
        p = head.next
        if pre != p.val:
            r.next = head
            r = r.next
        while p:
            if p.val != pre and (p.next is None or p.val != p.next.val):
                r.next = p
                r = r.next
            pre = p.val
            p = p.next
        r.next = None
        return rhead.next           

日期: 2020-11-17 周二就又过去了半天

原文地址:https://www.cnblogs.com/wangyuxia/p/13993602.html