Find the length of a linked list
Iterative solution:
- The key point here is initialize count = 0 and currentNode = head.
- Increment counter when currentNode != null.
- currentNode = currentNode->next
Code:
int count (Node head){
currentNode = head;
int count = 0;
while(currentNode != null){
count++;
currentNode = currentNode->next;
}
return count;
}
Recursive solution:
- Recursively call 1+getCount(Node head)
- 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
Post a Comment