Find Length of a Linked List ( Iterative and Recursive ) | Node class ; Linked List class contains a Node object ; Function to initialize head ; This function is in LinkedList class . It inserts a new node at the beginning of Linked 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 ; This function counts number of nodes in Linked List recursively , given ' node ' as starting node . ; Base case ; Count is this node plus rest of the list ; A wrapper over getCountRec ( ) ; Code execution starts here ; Start with the empty list
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT class LinkedList : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . head = None NEW_LINE DEDENT def push ( self , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . next = self . head NEW_LINE self . head = new_node NEW_LINE DEDENT def getCountRec ( self , node ) : NEW_LINE INDENT if ( not node ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 + self . getCountRec ( node . next ) NEW_LINE DEDENT DEDENT def getCount ( self ) : NEW_LINE INDENT return self . getCountRec ( self . head ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT llist = LinkedList ( ) NEW_LINE llist . push ( 1 ) NEW_LINE llist . push ( 3 ) NEW_LINE llist . push ( 1 ) NEW_LINE llist . push ( 2 ) NEW_LINE llist . push ( 1 ) NEW_LINE print ' Count ▁ of ▁ nodes ▁ is ▁ : ' , llist . getCount ( ) NEW_LINE DEDENT