Saturday, June 19, 2021
Home coding Write a program to find a length of linkedlist

Write a program to find a length of linkedlist

Given a linkedlist,we have to find the length of a linkedlist.

Example:

Input: 1 2 3 4 5 6
Output:6

Logic:

STEP 1:start traversing a linkedlist with a node head till be reach end of the linkedlist.
STEP 2:increment count variable while traversing the node.
STEP 3:return the count .

Code

int lengthofLinkedlist(Node *head)
{
    if(head==NULL)
    {
        return;
    }
    int count=0;
    while(head!=NULL)
    {
       count++;
        head=head->next;
    }
   return count; 
    
}

Ouput:

1 2 3 4 5 6
6

Time Complexity:O(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments