如何计算链表中的节点数



这是我的代码,但我无法计算列表中的节点,我还给出了下面的测试用例,这些测试用例应该执行

class LinkedList:
def __init__(self, a):
self.head = None
tail=None
list=[]
for x in a:
if x not in list:
list+=[x]
if len(a)!=len(list):
print("all keys are not unique")
if len(a)==0:
print("Array is empty.")
else:
for x in a:
newNode = Node(x, None)
if (self.head == None):
self.head = newNode
tail = newNode
else:
tail.next = newNode
tail = newNode

# Count the number of nodes in the list
def countNode(self):
self.head= None

pass # Remove this line

测试用例

print("////// Test 01 //////")
a1 = [10, 20, 30, 40]
h1 = LinkedList(a1) # Creates a linked list using the values from the array
# head will refer to the Node that contains the element from a[0]
h1.printList() # This should print: 10,20,30,40
print(h1.countNode()) # This should print: 4

我假设您的Node看起来像这个

class Node:
def __init__(self, val, next_=None):
self.element = val
self.next = next_ # you should use next_ 

@property
def countNode(self):
temp = self.head
cnt = 0
while temp:
cnt += 1
temp = temp.next

def printList(self):
temp = self.head
while temp:
print(temp.element)  # if Node contains val for value
temp = temp.next

配合你的代码,

h1 = LinkedList(a1)
# for count -> h1.countNode
# for print -> h1.printList()

最新更新