【leetcode】Python实现-83.删除排序链表中的重复元素

83.删除排序链表中的重复元素

描述

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例1

输入: 1->1->2
输出: 1->2

示例2

输入: 1->1->2->3->3
输出: 1->2->3

        if not head:
            return None
        p = head
        if p.next == None:
            return head
        try:
            while p.next:
                i = p.val
                if p.next.val == i:
                    p.next = p.next.next
                    while p.next:
                        if p.next.val != i:
                            break
                        p.next = p.next.next
                p = p.next
        except AttributeError:
            return head
        else:
            return head

写了两三个小时吧,一直改改改。搞得最后逻辑都不是很清楚了,所以引入了异常处理。。。。。然后发现leetcode中输入示例中[1,2,3]头节点是指1.所以返回的是head而不是head.next。
别人的if…else判断一目了然,逻辑很清晰。

class Solution:
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None:
            return None
        cur = head
        while cur.next:

            if cur.val == cur.next.val:
                if cur.next.next is None:
                    cur.next = None
                else:
                    temp = cur.next.next
                    cur.next = temp
            else:
                cur = cur.next

        return head

猜你喜欢

转载自blog.csdn.net/qq_34364995/article/details/80284364