Remove Duplicates

题目描述

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

解题方法

这一题要保留一个重复的元素,不过我们也可以用Dummy node的方法来解。 因为要判断dummy的后两个Node是否重复,所以要涉及两个元素,如果后面只剩下cur.next,那后面也就不会有重复了。所以 while loop的条件是while cur.next and cur.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:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return dummy.next

Reference