Remove Duplicates from Sorted List II

Problem: Remove Duplicates from Sorted List II

The key point is to find previous node of duplicates and following node of duplicates and connect them together.

Code in Python:

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

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prev = dummy = ListNode(0)
        dummy.next = head
        while head and head.next:
            if head.val != head.next.val:
                prev, head = head, head.next
            else:
                while head.next and head.val == head.next.val:
                    head = head.next
                prev.next, head = head.next, head.next
        return dummy.next

results matching ""

    No results matching ""