计算链接列表节点

时间:2019-06-05 09:04:05

标签: python python-3.x

当节点值为非负奇数时,我正在尝试计算链接列表中的节点数,但是似乎无法获得正确的结果。

class Solution:
    """
    @param head: 
    @return: nothing
    """
    def countNodesII(self, head):
        count = 0
        while head.next is not None:
            head = head.next
            if head.val > 0 and head.val % 2 != 0:
                count += 1 
            else:
                return 0
        return count

如果输入为1-> 3-> 5-> null 我希望得到3的结果,但是我的程序却返回2。

1 个答案:

答案 0 :(得分:2)

代码中的某些问题

  • 检查条件的头节点后,您想通过head=head.next移至下一个节点,现在您正在跳过head

  • 您可能希望从其他地方删除return,而只在最后返回count

  • 您要检查head是否达到None,因为您正在使用它来遍历列表

所以更新后的代码看起来像

class Solution:
    """
    @param head: 
    @return: nothing
    """
    def countNodesII(self, head):
        count = 0
        #Iterate over the list
        while head != None:
            #Check for condition
            if head.val > 0 and head.val % 2 != 0:
                count += 1
            #Move to next node
            head = head.next
        return count