How can we measure the length of a 'ListNode'?

  • 0

    if we use len() it will return the following error:
    TypeError: object of type 'NoneType' has no len()
    So my question is for singly-linked list like this:

    class ListNode:

    def init(self, x):

    self.val = x = None

    How can we calculate the length?

  • 0

    Maybe you should go next from the head node to the tail node, calculate the count.

  • 0

    or you can create your own ListNode class, give it a len method, and use to calculate how many nodes in that ListNode, then you can use len(node)

  • 0

    @Shangrila The ListNode used in Leetcode does not support iteration or len() method. As indicated by the comment, it only has .val and .next. So if you want to know the length, the only way is to walk the list (while list: list = But you may also consider how you solve the problem. It may be solved while walking through the ListNode.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.