Length of Linked List
Problem Statement:β
-
Example:
β Solution: Iterative Traversalβ
int getLength(SinglyLinkedListNode* head) {
int length = 0;
SinglyLinkedListNode* current = head;
// Traverse the list and count nodes
while(current != nullptr) {
length++;
current = current->next;
}
return length;
}
π How It Worksβ
- We start with a pointer
currentat the head. - For every node we visit, we increment
lengthby 1. - When
currentbecomesnullptr(end of list), we stop and return the count.
This is a simple linear traversal from head to tail.
π§© Key Logicβ
Thereβs no recurrence or DP here β just this iterative loop:
while(current != nullptr) {
length++;
current = current->next;
}
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| π Time | O(N), where N is the number of nodes |
| π§ Space | O(1), constant space |
β οΈ Edge Casesβ
- Empty list (
head == nullptr) β Length is 0 - Single node β Length is 1
π‘ Other Approachesβ
| Approach | Time | Space | Notes |
|---|---|---|---|
| Iterative β | O(N) | O(1) | Most efficient and preferred |
| Recursive | O(N) | O(N) | Adds call stack space (not ideal) |
π Related Problemsβ
- Detect Length of Cycle in Linked List (Floydβs Cycle Detection)
- Remove N-th Node from End (need length first)
- Check if Length is Even or Odd
- Reverse a Linked List
π¬