Counting all the nodes in a Linked List

后端 未结 9 1287
失恋的感觉
失恋的感觉 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条回答
  •  -上瘾入骨i
    2020-12-22 04:50

    You should check for null first. If not 0, then set 'counter = 1' before you loop through it.

    if (_first == null) return 0;
                int count = 1;
                for (ListNode n = _first; n.Next != null; n = n.Next)
                {
                    count++;
                }
                return count;
    

提交回复
热议问题