2017-08-04 50 views
0

下面是我的函数removeOdds,它删除链接列表中的所有奇数节点。减少摆脱链表中奇数节点的方法Python 3

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 

我在想,如果有,我删除最后一个节点,如果是奇数和点无没有我不得不退出while循环的方式。 为了清楚起见,我的链接列表看起来像嵌套字典。 ex。

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

回答

0

如果你改变了回路同时实现真正的,移动测试没有进入死循环,并利用假期的适当条件下退出循环,我想你会发现,你不必循环外的重复代码。