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 povar to new Node ; Returns count of nodes in linked list ; Base case ; Count is this node plus rest of the list ; Wrapper over getCountRec ( ) ; Start with the empty list
class Node { constructor ( val ) { this . data = val ; this . next = null ; } } var head ; function push ( new_data ) { var new_node = new Node ( new_data ) ; new_node . next = head ; head = new_node ; } function getCountRec ( node ) { if ( node == null ) return 0 ; return 1 + getCountRec ( node . next ) ; } function getCount ( ) { return getCountRec ( head ) ; } push ( 1 ) ; push ( 3 ) ; push ( 1 ) ; push ( 2 ) ; push ( 1 ) ; document . write ( " " + getCount ( ) ) ;