python怎么获取链表长度

41次阅读
没有评论

共计 478 个字符,预计需要花费 2 分钟才能阅读完成。

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

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-16发表,共计478字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)