2020-09-22 11:06:57 +08:00
|
|
|
package DataStructures.Lists;
|
|
|
|
|
|
|
|
public class CountSinglyLinkedListRecursion extends SinglyLinkedList {
|
2020-10-24 18:23:28 +08:00
|
|
|
public static void main(String[] args) {
|
|
|
|
CountSinglyLinkedListRecursion list = new CountSinglyLinkedListRecursion();
|
|
|
|
for (int i = 1; i <= 5; ++i) {
|
|
|
|
list.insert(i);
|
2020-09-22 11:06:57 +08:00
|
|
|
}
|
2020-10-24 18:23:28 +08:00
|
|
|
assert list.count() == 5;
|
|
|
|
}
|
2020-09-22 11:06:57 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
/**
|
|
|
|
* Calculate the count of the list manually using recursion.
|
|
|
|
*
|
|
|
|
* @param head head of the list.
|
|
|
|
* @return count of the list.
|
|
|
|
*/
|
|
|
|
private int countRecursion(Node head) {
|
|
|
|
return head == null ? 0 : 1 + countRecursion(head.next);
|
|
|
|
}
|
2021-04-09 22:19:34 +08:00
|
|
|
/** Returns the count of the list. */
|
2020-10-24 18:23:28 +08:00
|
|
|
@Override
|
|
|
|
public int count() {
|
|
|
|
return countRecursion(getHead());
|
|
|
|
}
|
2020-09-22 11:06:57 +08:00
|
|
|
}
|