温馨提示×

python怎么获取链表长度

小亿
230
2023-10-26 23:02:23
栏目: 编程语言

要获取链表的长度,可以先定义一个计数器,然后遍历链表,每遇到一个节点,计数器加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

0