Calculating the number of nodes in a singly linked list.
To get the length of a singly linked list, we traverse the list from the head and count each node until we reach the end of the list (null).
This operation does not require random access or indexing; we simply move forward using the next pointers while incrementing a counter.
Suppose we have a singly linked list with the following values:
We want to calculate the length of the list by traversing it node by node and counting.
5), count = 1.
15, count = 2.
25, count = 3.
35, count = 4.
45, count = 5.
We reach the end of the list. Total count = 5. This is the length of the singly linked list.
This pseudocode shows how to calculate the length of a singly linked list by traversing it from start to end and counting the nodes.
function getLength(head):
curr = head
length = 0
while curr != null:
length += 1
curr = curr.next
return length
Let’s understand each part of the code step by step.
function getLength(head):
curr = head
length = 0
Explanation: We define the function and initialize two variables — curr to traverse the list and length to count nodes.
while curr != null:
length += 1
curr = curr.next
Explanation: We loop through the list, incrementing length for every node we visit and moving curr forward.
return length
Explanation: Once the loop finishes (i.e., we've visited every node), we return the total length of the list.
The following examples demonstrate how to calculate the length of a singly linked list.
| Initial List | Length | Explanation |
|---|---|---|
| [10, 20, 30, 40, 50] | 5 | Start from the head and count each node until reaching null. |
| [5, 15, 25] | 3 | Three nodes are present in the list. Traverse and increment count by one for each. |
| [1] | 1 | Single node present. Length is 1. |
| [] | 0 | List is empty. Head is null, so the length is 0. |
| Length Calculation Case | Time Complexity | Explanation |
|---|---|---|
| Empty List | O(1) | We immediately check if the head is null and return 0. |
| Non-Empty List | O(n) | We traverse each node once from head to tail to count the total number of nodes. |
| Length Calculation | Space Complexity | Explanation |
|---|---|---|
| Get Length | O(1) | We use a single counter and a pointer variable to traverse the list. No additional space is required, regardless of the list size. |