LeetCode 问题已从排序列表中删除重复项

问题描述 投票:0回答:1

我尝试了通过 head 的方法,将其与我制作的新 ListNode 的 curr 进行比较。如果它尚不存在,请添加它。但是,看起来它对于重复项不能正常工作,因此我将策略切换为将整个头复制到新的 ListNode 中,并更新 curr.next(如果它等于 curr 的值)到 curr.next.next ,这有效。但是,我仍然想弄清楚为什么我以前的方法/策略不起作用以及如何修复它。 之前的策略我无法开始工作:

class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
    return None

    temp = ListNode()
     curr = temp
    
        while head:
            if head.val != curr.val:
                curr.next = head
                head = head.next
                curr = curr.next
            else:
                head = head.next
        return temp.next

失败的示例:

head = \[1,1,2,3,3\]

我的输出

\[1,2,3,3\]

预计

\[1,2,3\]

它只进入我的 if 语句 3 次,因为当我在 curr = curr.next 下有一个打印语句时,它只打印 1,2,3。然而,当它打印最终产品时,不知怎的,它又得到了 3。

为了解决这个问题,我在 temp.next 之前添加了 curr.next = None ,但这在 head = [0,0,0] 时不起作用

python linked-list
1个回答
0
投票

这是一个链表类,有成员 head、tail、size:

    def remove_duplicates(self):
        if(self.head is None or self.head.next is None):
            return self.head
        curr = self.head
        self.head = None
        while(True):
            next = curr.next
            while(next is not None and curr.data == next.data):
                self.size -= 1
                next = next.next
                curr.next = next
            if(self.head is None):
                self.head = curr;
            if(next is None):
                break
            curr = curr.next
        self.tail = curr
        return
© www.soinside.com 2019 - 2024. All rights reserved.