# Find Length Of A Linked List Iterative And Recursive

### Problem statement

Given a singly linked list, find its length.

Input: Output: 4.
As there are 4 nodes in the linked list.

Input: Output: 0.
As there is no node in the linked list.

How do we define the length of a linked list?
The length of a linked list is the total number of nodes in it.

### Approach (Iterative)

We know how to iterate through the linked list. In an iteration, we visit each node exactly once. We can keep track of the count of each node visited and that will be the length of the linked list.

### Algorithm

• Iterate through the linked list and for each iteration increment the answer by 1.
• After the iteration completes, return the answer.

### Implementation:

```using namespace std;

struct Node {
int val;
Node* next;

Node(int value){
val = value;
next = NULL;
}
};

Node* new_node = new Node(new_val);
}

// function to find length of a linked list
}
}

int main(){

cout<

```

#### Output

4

Time complexity: O(n), since we are traversing the linked list once.
Space complexity: O(1), as we aren’t using any extra space.
Here, ‘n’ is the number of nodes in the linked list.

### Approach (Recursive)

To solve this problem recursively, we need to break this problem down into subproblems as we do in all recursive approaches.

For a given node of a linked list, we know it will contribute 1 to the total length. So, now we need to find the length of the linked list following the current node and add 1 to it. Finding the length of the remaining list can be seen as the same problem and hence can be solved by calling the same function for the next node.

So, the length of a linked list with ‘head’ as a pointer to 1st node can be written as: length(head) = 1 + length(head->next)

The length will be 0 for an empty linked list. This can be used as the base case in our recursive function. Since it is clear what we need to do, take some time and think about how we are going to do it.

### Algorithm

• If head points to NULL, return 0. (base case)
• Else recursively call the same function for head->next and add 1 to its result.

### Implementation

```using namespace std;

struct Node {
int val;
Node* next;

Node(int value){
val = value;
next = NULL;
}
};

Node* new_node = new Node(new_val);
}

}

int main(){

cout<

```

#### Output

4

Time complexity: O(n), as we are completely traversing the linked list once.
Space complexity: O(n), due to recursive function call stack.

Here ‘n’ is the number of nodes in the linked list.

Through this article, we learned how to find the length of a singly linked list using both iterative and recursive methods. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link Linked List.