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
>>>
我需要在此程序中包含一种计算列表中特定数据的次数的方法。那么我怎样才能创建一个显示" Dog"在列表中两次?
答案 0 :(得分:0)
你快到了。只要看到给定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"))