You can also use this:
def len_link(list):
temp=list.head
count=0
while(temp):
count+=1
temp=temp.next
return count
Answer from Nitika Khurana on Stack OverflowHello!
We are creating Stacks implemented as a linked list. One of the methods of my stack should be to return its length.
My code currently works if the length of the stack is 1 or 0, but not for anything longer. I suspect the problem to be that once the head is checked, it is not moving onto the next Node correctly.
However, why would this be? (In a length of one item), Why is it that it can move from 1 item, to the None item and return a correct list of 1, but not anything more than that?
Please see my code below (let me know if you would need more):
def __len__(self):
""" Returns the length --- calling len(s) will invoke this method ""
inspector = self.head #inspector is what I've named the item being checked
if inspector == None: #the last element of the linked list is None, so length = 0
return 0
counter = 0
while inspector != None:
counter += 1
inspector = self.head.next_node #I assume this is the part which is causing the issue
return counter I'm going to catch some Zzz's (this has kept me up too late!) So i will reply in the morning, please let me know if you would like any more information.
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.
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