在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 is not None:
count += 1
current = current.next
return count
在这个示例中,`ListNode` 类定义了链表节点,每个节点包含一个值 `val` 和一个指向下一个节点的指针 `next`。`get_length` 函数接受链表的头节点 `head` 作为参数,通过遍历链表并计数来获取链表的长度。
