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:
def init(self, x):
self.val = x
self.next = None
How can we calculate the length?
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)
@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.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.