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


  • 0
    W

    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

    self.next = None

    How can we calculate the length?


  • 0
    S

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


  • 0
    I

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


  • 0
    R

    @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 = list.next). 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.