摆脱链表 Python 3 中奇数节点的不那么复杂的方法



下面是我的函数 removeOdds,它删除链表中的所有奇数节点。

def removeOdds(myList):
head=myList
ptr=head
counter=1
while ptr['next']['next']!=None:
if counter %2 != 0:
ptr['data'] = ptr['next']['data']
ptr['next'] = ptr['next']['next']
counter += 1
else:
ptr = ptr['next']
counter += 1
counter += 1
if counter %2 != 0:
ptr['next'] = None
return head

我想知道是否有办法删除最后一个节点,如果它很奇怪并且指向 None,而无需我退出 while 循环。 为了清楚起见,我的链表看起来像嵌套词典。 前任。

{'data': 9, 'next': {'data': 8, 'next': {'data': 6, 'next': {'data': 5,
'next': {'data': 3, 'next': {'data': 2, 'next': {'data': 1, 'next': 
None}}}}}}}

如果将循环更改为 while True,将 None 的测试移动到循环中,并在适当的条件下使用 break 退出循环,我想你会发现你不必在循环之外复制代码。

最新更新