1

I have a linked-list and I want to calculate it's length with a function, here's my definition :

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None
11
  • 3
    Ok, where's your code that attempts to calculate the length? Commented Aug 7, 2017 at 19:28
  • 1
    Why not, in your linked-list class, have a variable that increments and decrements when you add or remove nodes to and from the list? Commented Aug 7, 2017 at 19:29
  • @RagingRoosevelt because you can't do that in any sensible way with a singly linked list. Commented Aug 7, 2017 at 19:32
  • 1
    I didn't know how to approach it, and I thought it's simple task to those who know, so it's okay to ask for the code without writing it. Commented Aug 7, 2017 at 19:32
  • 2
    @HiDay it's not. SO is not a code-writing service, and questions like these are very likely to get closed. Commented Aug 7, 2017 at 19:34

2 Answers 2

3

Try this function:

def length(lst):
    r = 0
    while lst:
        lst = lst.next
        r += 1
    return r # 'r' being the length

It works by moving forward along the list counting the number of nodes observed until a None link is encountered.

Sign up to request clarification or add additional context in comments.

Comments

2

You can simply set the head node to a variable, and continuous count until you hit the point where temp == NULL

def height(list):
    temp=list.head
    count=0
    while temp:
        count+=1
        temp=temp.next
    return count

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.