1. 程式人生 > >【leetcode】Python實現-83.刪除排序連結串列中的重複元素

【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