mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 09:06:51 +08:00
Enhance docs, remove main
, add tests in `CountSinglyLinke… (#5992)
This commit is contained in:
@ -1,27 +1,26 @@
|
||||
package com.thealgorithms.datastructures.lists;
|
||||
|
||||
/**
|
||||
* CountSinglyLinkedListRecursion extends a singly linked list to include a
|
||||
* recursive count method, which calculates the number of nodes in the list.
|
||||
*/
|
||||
public class CountSinglyLinkedListRecursion extends SinglyLinkedList {
|
||||
|
||||
public static void main(String[] args) {
|
||||
CountSinglyLinkedListRecursion list = new CountSinglyLinkedListRecursion();
|
||||
for (int i = 1; i <= 5; ++i) {
|
||||
list.insert(i);
|
||||
}
|
||||
assert list.count() == 5;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the count of the list manually using recursion.
|
||||
* Recursively calculates the number of nodes in the list.
|
||||
*
|
||||
* @param head head of the list.
|
||||
* @return count of the list.
|
||||
* @param head the head node of the list segment being counted.
|
||||
* @return the count of nodes from the given head node onward.
|
||||
*/
|
||||
private int countRecursion(Node head) {
|
||||
return head == null ? 0 : 1 + countRecursion(head.next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the count of the list.
|
||||
* Returns the total number of nodes in the list by invoking the recursive
|
||||
* count helper method.
|
||||
*
|
||||
* @return the total node count in the list.
|
||||
*/
|
||||
@Override
|
||||
public int count() {
|
||||
|
Reference in New Issue
Block a user