Find Length of a Linked List ( Iterative and Recursive ) | Linked list Node ; Linked List class ; head of list ; Inserts a new Node at front of the list . ; 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new Node as head ; 4. Move the head to point to new Node ; Returns count of nodes in linked list ; Base case ; Count is this node plus rest of the list ; Wrapper over getCountRec ( ) ; Driver program to test above functions . Ideally this function should be in a separate user class . It is kept here to keep code compact ; Start with the empty list
class Node { int data ; Node next ; Node ( int d ) { data = d ; next = null ; } } class LinkedList { Node head ; public void push ( int new_data ) { Node new_node = new Node ( new_data ) ; new_node . next = head ; head = new_node ; } public int getCountRec ( Node node ) { if ( node == null ) return 0 ; return 1 + getCountRec ( node . next ) ; } public int getCount ( ) { return getCountRec ( head ) ; } public static void main ( String [ ] args ) { 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 ▁ " + llist . getCount ( ) ) ; } }