Skip to main content

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 current at the head.
  • For every node we visit, we increment length by 1.
  • When current becomes nullptr (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​

MetricValue
πŸ•’ TimeO(N), where N is the number of nodes
🧠 SpaceO(1), constant space

⚠️ Edge Cases​

  • Empty list (head == nullptr) β†’ Length is 0
  • Single node β†’ Length is 1

πŸ’‘ Other Approaches​

ApproachTimeSpaceNotes
Iterative βœ…O(N)O(1)Most efficient and preferred
RecursiveO(N)O(N)Adds call stack space (not ideal)

  • 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

πŸ’¬

Discussion & Doubts