Counting all the nodes in a Linked List

后端 未结 9 1321
失恋的感觉
失恋的感觉 2020-12-22 04:25

I\'m trying to write a simple method to count all the nodes in the linked list. I know there are 7 items in the linked list, but it is returning just 6 of them.

Her

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-22 04:42

    n.next != null Is your problem. Change it to n!=null

     Example : 
    
    List : 1--> 2 -->3--> 4-->null
    Count :  1--> 2-->3-->here n=4 and n.next=null. So, your loop will break and count will be 3 (i.e; the last node will not be counted.)
    

提交回复
热议问题