Posted on by Kalkicode

# Find length of Doubly Linked List

The problem presented here involves finding the length of a doubly linked list. A doubly linked list is a linear data structure consisting of nodes, where each node contains a value, a reference to the next node, and a reference to the previous node. The length of a linked list refers to the number of nodes present in it.

## Problem Statement

Given a doubly linked list, we are required to determine its length. In other words, we need to count the number of nodes in the list.

## Example

Let's consider an example to understand the problem. Suppose we have a doubly linked list with the following values: 4, 3, 2, 5, 3. The length of this list is 5, as it contains five nodes.

## Idea to Solve

To find the length of a doubly linked list, we need to traverse through the list while counting the nodes encountered. Starting from the head of the list, we will move from one node to the next node until we reach the end of the list. At each step, we will increment a counter that keeps track of the number of nodes visited. Once we have traversed the entire list, the counter will contain the length of the list.

## Pseudocode

Here's the pseudocode that outlines the algorithm to find the length of a doubly linked list:

``````function length():
size = 0
while current is not null:
size += 1
current = current.next
return size``````

## Algorithm Explanation

• We start with a variable `size` initialized to 0. This variable will hold the length of the linked list.
• We then initialize a `current` pointer with the head of the linked list.
• We enter a loop that iterates as long as the `current` pointer is not null.
• Inside the loop, we increment the `size` variable by 1 for each node we visit.
• We then move the `current` pointer to the next node.
• After traversing the entire list, the `size` variable will contain the length of the linked list.

## Time Complexity

• The algorithm traverses through the entire linked list once.
• The time complexity of this algorithm is O(n), where n is the number of nodes in the linked list.

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

Categories
Relative Post