要獲取鏈表的長度,可以先定義一個計數器,然后遍歷鏈表,每遇到一個節點,計數器加1。最后返回計數器的值即可。
以下是一個示例代碼:
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
# 創建一個鏈表:1 -> 2 -> 3 -> 4 -> 5
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