在Python中,求链表长度通常需要遍历链表并计数。以下是一个示例代码,展示了如何定义链表节点类以及一个函数来获取链表的长度:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def get_length(head):
count = 0
current = head
while current:
count += 1
current = current.next
return count
创建一个链表
head = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
head.next = node2
node2.next = node3
node3.next = node4
node4.next = node5

获取链表长度
length = get_length(head)
print("链表长度为:", length)
输出结果为:```链表长度为: 5
这段代码定义了一个`ListNode`类来表示链表中的节点,每个节点包含一个值和一个指向下一个节点的指针。`get_length`函数遍历链表,每遇到一个节点,计数器加1,最后返回计数器的值,即链表的长度。
