Python 对于列表,我需要返回什么?对于edge case duplicate,我需要代码吗?
我有以下Python 对于列表,我需要返回什么?对于edge case duplicate,我需要代码吗?,python,linked-list,Python,Linked List,我有以下ListNode类: class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next 我编写以下代码的目的是从链接列表中删除任何重复项: def deleteDuplicates(self, head: ListNode) -> ListNode: if head == None: return
ListNode
类:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
我编写以下代码的目的是从链接列表中删除任何重复项:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head == None:
return None
if head.next == None:
return head
curr = head
nex = head.next
while nex:
if head.val == nex.val:
curr.next = nex.next
curr = nex.next
nex = curr.next
问题:
我将假定您的列表总是经过排序的,因此任何重复项在列表中总是挨着一个
while
循环中存在两个问题:
if head.val == nex.val:
curr = nex.next
到
curr=nex.next
跳过节点。这意味着curr
永远不会是nex
。这也意味着下一条语句可能是无效引用,因为curr
可能是None
。因此,改变:
if head.val == nex.val:
curr = nex.next
到
nex
应移动到下一个节点curr
应保持原样,因为它可能有多个副本需要处理。因此,上述分配给curr
的任务应该只在您没有重复项的情况下发生
while
循环如下:
while nex:
if curr.val == nex.val:
curr.next = nex.next
else:
curr = nex
nex = curr.next
还什么
由于您的函数似乎被设计为返回一个ListNode
,只需确保始终返回head
。因此,在while
循环之后也添加该语句
在我看来,这个函数不必返回head节点,因为head
的值永远不会因这个函数而改变。因此,调用方已经知道该值
注意:您不需要专门处理此案例:
if head.next == None:
return head
这种情况只意味着while
循环不会有一次迭代。如上所述,只需在函数的最后添加一个return语句,然后您就可以删除上面的if
块:
return head
您的示例显示了已排序的列表,因此总是有重复项彼此相邻。我们必须假定列表已排序吗?另外,
deleteDuplicates
的self
参数是什么?你从来没有提到过它…非常感谢你,特林科特,你的解释非常清楚,我完全理解。我真的很感谢你花时间写评论。干杯,帕特里克