计算链表中的值的数量

时间:2013-10-11 05:02:43

标签: python python-2.7

我的countInt功能有问题。除了它被标记为countINT并且将'-'作为参数放入其中之外。我测试了我的链表的创建,它似乎正常工作。因此我觉得我可以安全地将其排除在外。但是,由于NoneType对象没有属性值错误,我不确定我哪里出错了。有人可以成为我的另一双眼睛,帮我挑出错误并指导我纠正它吗?非常感谢!

输出:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "linked_list.py", line 63, in <module>
    print countInt(r,1)
  File "linked_list.py", line 25, in countInt
    countInt(head.next,n)
  File "linked_list.py", line 25, in countInt
    countInt(head.next,n)
  File "linked_list.py", line 25, in countInt
    countInt(head.next,n)
  File "linked_list.py", line 25, in countInt
    countInt(head.next,n)
  File "linked_list.py", line 25, in countInt
    countInt(head.next,n)
  File "linked_list.py", line 25, in countInt
    countInt(head.next,n)
  File "linked_list.py", line 25, in countInt
    countInt(head.next,n)
  File "linked_list.py", line 25, in countInt
    countInt(head.next,n)
  File "linked_list.py", line 25, in countInt
    countInt(head.next,n)
  File "linked_list.py", line 25, in countInt
    countInt(head.next,n)
  File "linked_list.py", line 25, in countInt
    countInt(head.next,n)
  File "linked_list.py", line 25, in countInt
    countInt(head.next,n)
  File "linked_list.py", line 23, in countInt
    if head.next.value == n:
AttributeError: 'NoneType' object has no attribute 'value'

预期产出:

2
2

我的代码:

class Node:
    def __init__(self,value):
        self.next = None
        self.value = value

def createLinkedList(root, node):
    if root.next is None:
        root.next = node
    else:
        createLinkedList(root.next, node)

def countInt(head, n, count= 0):        #create a dictionary with keys as the values of the linked list and count up if the value occurs again
    count = 0
    if head.value is None:
        return None
    else:
        if head.next.value == n:
            count += 1
        countInt(head.next, n, count)
        return count


# root
r = Node(1)

# nodes
a = Node(4)
b = Node(1)
c = Node(5)
d = Node('-')
e = Node(4)
f = Node(1)
g = Node(2)
h = Node('-')
i = Node(8)
j = Node(9)
k = Node(8)
l = Node(3)

createLinkedList(r,a)
createLinkedList(r,b)
createLinkedList(r,c)
createLinkedList(r,d)
createLinkedList(r,e)
createLinkedList(r,f)
createLinkedList(r,g)
createLinkedList(r,h)
createLinkedList(r,i)
createLinkedList(r,j)
createLinkedList(r,k)
createLinkedList(r,l)


print countInt(r,1)
print countInt(r,'-')

1 个答案:

答案 0 :(得分:2)

更改行:

if head.value is None:

if head.next is None:

该行的目的是知道列表何时应该停止,此时下一个节点将是None。存储在节点中的值与此无关:最后一个节点仍然具有值(相反,您可能希望在列表中较早地存储值None。)


作为一个单独的问题,你的函数将始终返回0.行countInt(head.next, n, count)实际上并没有对变量count做任何事情:Python按值传递int,所以你传递的变量赢了' t增加。甚至一旦你解决了这个问题,你总是检查head.next的事实意味着你正在跳过列表中的第一个元素。您应该将您的功能设置为:

def countInt(head, n):
    count = 0
    if head.value == n:
        count = 1
    if head.next is None:
        return count
    return count + countInt(head.next, n)

这实际上可以让你摆脱通过列表传递count(这是实现递归的一种尴尬方式)。