Remove Duplicates II

题目描述

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

For example, Given 1->2->3->3->4->4->5, return 1->2->5. Given 1->1->1->2->3, return 2->3.

解题方法

这一题要去除所有重复的元素,head不能确定是否保留,所以要用Dummy node。 与1不同的是,要去掉所有重复的元素,记录下这个重复的点的value, 那么就要改重复元素的前一点的next, 而且要不断地向后判断重复元素结束的地方,再设next。

Solution

# 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
        """
        if not head:
            return None
        dummy = ListNode(0)
        dummy.next = head
        cur = dummy
        while cur.next and cur.next.next:
            if cur.next.val == cur.next.next.val:
                # keep the duplicates value
                curVal = cur.next.val
                # find all the duplicates
                # set the cur.next to the node after these duplicates
                while cur.next and cur.next.val == curVal:
                    cur.next = cur.next.next
            else:
                cur = cur.next
        return dummy.next

Reference