
非递归版本:
class ListNode:
def __init__(self, x,next=None):
self.val = x
self.next = next
def sortInList(head):
cout=0
while head:
cout+=1
head = head.next
return cout
if __name__ == '__main__':
root=ListNode(1,ListNode(2,ListNode(3,ListNode(4,ListNode(5,None)))))
len=sortInList(root)
print('The length of the linked list is ' + str(len))
递归版本:
class ListNode:
def __init__(self, x,next=None):
self.val = x
self.next = next
def sortInList(head,cout):
if head:
cout+=1
head=head.next
else:
return cout
return sortInList(head,cout)
if __name__ == '__main__':
root=ListNode(1,ListNode(2,ListNode(3,ListNode(4,ListNode(5,None)))))
cout = 0
len=sortInList(root,cout)# 输入头节点
print('The length of the linked list is ' + str(len))
本文提供两种计算链表长度的方法:非递归版本通过遍历整个链表来计算节点数量;递归版本则采用递归调用的方式进行计算。这两种方法均适用于单链表的数据结构。
7万+

被折叠的 条评论
为什么被折叠?



