class Node:
def __init__(self, data):
self.data = data
self.next = None
head = Node("Cat")
another_node = Node("Dog")
head.next = another_node
a_third_node = Node("Bird")
another_node.next = a_third_node
last_node = Node("Dog")
a_third_node.next = last_node
node = head # copy the address of the head node into node
while node != None:
print ("List item: ", node.data)
node = node.next
对于上面的代码,我得到以下输出:
>>>
List item: Cat
List item: Dog
List item: Bird
List item: Dog
>>>
我需要在这个程序中包括一种计算特定数据在列表中出现的次数的方法。那么如何创建一个计数器来显示"狗"在列表中两次呢?
你快到了。只需在看到给定的value
时递增一个计数器变量,而不仅仅是打印数据:
def count(head, value):
seen = 0
while head is not None:
if head.data == value:
seen += 1
head = head.next
return seen
#...
print(count(head, "Dog"))