Counting all the nodes in a Linked List

后端 未结 9 1251
失恋的感觉
失恋的感觉 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++;
    }
    
    0 讨论(0)
  • 2020-12-22 04:33

    Well that's because you are starting your count from 0, neglecting the first node.

    Instead initialize count=1;

    0 讨论(0)
  • 2020-12-22 04:34

    I figured it out.

    for (ListNode n = head; n != null; n = n.next)
    

    n.next !=null was the error.

    0 讨论(0)
  • 2020-12-22 04:35

    You want to loop until n == null. As it stands, you're stopping one short.

    0 讨论(0)
  • 2020-12-22 04:37

    The end node will fail n.next != null but it is part the the LinkedList, so you should consider that. It sounds like you simply have an indexing error.

    0 讨论(0)
  • 2020-12-22 04:42

    try this

    public int count() {
        int count = 0;
        for (ListNode n = head; n != null; n = n.next) {
            count++;
        }
        return count;
    }
    
    0 讨论(0)
提交回复
热议问题