每日一题 【每日一题】计算链表节点数-Python-20211027

Jack · 2021年10月27日 · 最后由 Jack 回复于 2021年10月29日 · 66 次阅读
本帖已被设为精华帖!

计算一个链表中有多少个节点

Jack 将本帖设为了精华贴 10月27日 21:15

参考代码:

class ListNode(object):
    def __init__(self, val, next = None) -> None:
        self.val = val
        self.next = next
class Solution:
    def countNodes(self, head):
        cnt = 0
        while head is not None:
            cnt += 1
            head = head.next
        return cnt
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册