Measure the size / length of a single linked list in Java?
•
Java
I need help making int size(); The method of single linked list in Java
This is me so far, but it doesn't return the correct size of the list
public int size() { int size = 0; Node CurrNode = head; while(CurrNode.next != null) { CurrNode = CurrNode.next; size++; } return size; }
Can someone help me implement this method in Java?
Solution
The biggest improvement you can make is to use java coding convention and camelCase local variables
You can write like this
public int size() { int size = 0; for(Node n = head; n.next != null; n = n.next) size++; return size; }
When you rewrite a common class in Java, if you want a better way of doing things, I suggest you see how it is done
From LinkedList
/** * Returns the number of elements in this list. * * @return the number of elements in this list */ public int size() { return size; }
As you can see, when an element is added, the size increases, and when an element is deleted, it reduces the ID, saving you from having to traverse the list to get the size
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码