Find the length of a linked list

Iterative solution:

  1. The key point here is initialize count = 0 and currentNode = head. 
  2. Increment counter when currentNode != null.
  3. currentNode = currentNode->next
Code:

int count (Node head){
            currentNode = head;
            int count = 0;
            while(currentNode != null){
                   count++;
                   currentNode = currentNode->next;
             }
             return count;
}

Recursive solution:
  1. Recursively call 1+getCount(Node  head)
  2. If head is null return 0. Its the base condition.
Code:

int getCount(Node head){
             if( head == null )
                    return 0;
              return 1+getCount(head->next);
}

Comments

Popular posts from this blog

Tree traversals - Inorder Traversal

Binary Search tree (Insertion)

Stack implementation using array