Solution Review: Length of a Linked List
This lesson provides a detailed review of the solution to the challenge in the previous lesson.
We'll cover the following...
Solution: Length of a Linked List
Press + to interact
class Solution {/* Returns count of nodes in linked list */public static int lengthOfList(Node head){// Base caseif (head == null) {return 0;}// Recursive caseelse {return 1 + lengthOfList(head.next);}}public static void main(String[] args){/* Start with the empty list */LinkedList llist = new LinkedList();llist.push(1);llist.push(3);llist.push(1);llist.push(2);llist.push(1);System.out.println("Count of nodes is = " + lengthOfList(llist.head));}}
Understanding the Code
The code given above can be broken down into two parts. The recursive method and the main where the method is called.
Driver Method
The driver code is from line 17 to line 25.
-
In the driver code, from line 18 to ...