Counting all the nodes in a Linked List

后端 未结 9 1288
失恋的感觉
失恋的感觉 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:30

    You aren't counting the last node. When you get to the last element to be counted, n.next will be null, and so count is never incremented. You might instead try a loop like the following:

    ListNode n = head;
    for (ListNode n = head; n != null; n = n.next) {
      count++;
    }
    

提交回复
热议问题