非递归版本:
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))