Bird
Raised Fist0
DSA C++programming

Get Length of Linked List in DSA C++

Choose your learning style10 modes available
Mental Model
Count how many nodes are in the linked list by moving from the start to the end one by one.
Analogy: Like counting people in a line by walking from the first person to the last, counting each person you pass.
head -> 1 -> 2 -> 3 -> null
Dry Run Walkthrough
Input: list: 1 -> 2 -> 3 -> null
Goal: Find the total number of nodes in the list
Step 1: Start at head node with value 1, count = 0
head -> [curr->1] -> 2 -> 3 -> null, count=0
Why: We begin counting from the first node
Step 2: Count node 1, move curr to next node 2
head -> 1 -> [curr->2] -> 3 -> null, count=1
Why: Count current node before moving forward
Step 3: Count node 2, move curr to next node 3
head -> 1 -> 2 -> [curr->3] -> null, count=2
Why: Continue counting nodes one by one
Step 4: Count node 3, move curr to null (end)
head -> 1 -> 2 -> 3 -> [curr->null], count=3
Why: Count last node and reach end of list
Result:
head -> 1 -> 2 -> 3 -> null, length = 3
Annotated Code
DSA C++
#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;
    Node(int val) : data(val), next(nullptr) {}
};

int getLength(Node* head) {
    int count = 0;
    Node* curr = head;
    while (curr != nullptr) {
        count++; // count current node
        curr = curr->next; // move to next node
    }
    return count;
}

int main() {
    // Create linked list 1 -> 2 -> 3 -> null
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);

    int length = getLength(head);
    cout << "Length of linked list: " << length << endl;

    // Clean up memory
    Node* curr = head;
    while (curr != nullptr) {
        Node* temp = curr;
        curr = curr->next;
        delete temp;
    }
    return 0;
}
while (curr != nullptr) {
loop until we reach the end of the list
count++; // count current node
increment count for each node visited
curr = curr->next; // move to next node
advance pointer to next node
OutputSuccess
Length of linked list: 3
Complexity Analysis
Time: O(n) because we visit each node once to count
Space: O(1) because we use only a few variables regardless of list size
vs Alternative: Better than recursive counting which uses O(n) space for call stack
Edge Cases
empty list (head is nullptr)
returns 0 since there are no nodes
DSA C++
while (curr != nullptr) {
single node list
returns 1 as only one node is counted
DSA C++
while (curr != nullptr) {
When to Use This Pattern
When asked to find the size or count of elements in a linked list, use a simple traversal counting each node until the end.
Common Mistakes
Mistake: Forgetting to move the pointer to the next node inside the loop
Fix: Add 'curr = curr->next;' inside the while loop to advance traversal
Mistake: Starting count at 1 instead of 0, causing off-by-one error
Fix: Initialize count to 0 before counting nodes
Summary
Counts the number of nodes in a linked list by traversing it once.
Use when you need to know how many elements are in a linked list.
The key is to move through each node and count until you reach the end.

Practice

(1/5)
1. What does the function getLength do when given the head of a linked list?
easy
A. Deletes the linked list
B. Returns the value of the first node
C. Returns the number of nodes in the linked list
D. Returns the last node of the linked list

Solution

  1. Step 1: Understand the function purpose

    The function getLength counts nodes starting from the head until the end.
  2. Step 2: Identify the output

    It returns the total count of nodes, which is the length of the linked list.
  3. Final Answer:

    Returns the number of nodes in the linked list -> Option C
  4. Quick Check:

    Counting nodes = length [OK]
Hint: Count nodes one by one until null [OK]
Common Mistakes:
  • Confusing length with node value
  • Trying to delete nodes instead of counting
  • Returning the last node instead of count
2. Which of the following is the correct syntax to initialize a pointer to the head of a linked list in C++?
easy
A. Node* head = NULL;
B. Node head = NULL;
C. Node* head = 0;
D. Node head = 0;

Solution

  1. Step 1: Understand pointer initialization

    In C++, a pointer to a node is declared as Node* and can be initialized to NULL or nullptr.
  2. Step 2: Check each option

    Node* head = NULL; uses Node* head = NULL; which is correct pointer initialization syntax.
  3. Final Answer:

    Node* head = NULL; -> Option A
  4. Quick Check:

    Pointer declaration uses * and NULL [OK]
Hint: Use * for pointers and NULL for empty [OK]
Common Mistakes:
  • Declaring pointer without *
  • Assigning NULL to non-pointer variable
  • Using 0 instead of NULL (less clear)
3. What will be the output of the following code snippet?
struct Node {
  int data;
  Node* next;
};

int getLength(Node* head) {
  int count = 0;
  while (head != NULL) {
    count++;
    head = head->next;
  }
  return count;
}

int main() {
  Node n3 = {30, NULL};
  Node n2 = {20, &n3};
  Node n1 = {10, &n2};
  int length = getLength(&n1);
  std::cout << length;
  return 0;
}
medium
A. 3
B. 2
C. 1
D. 0

Solution

  1. Step 1: Trace the linked list nodes

    The list has nodes n1 -> n2 -> n3 -> NULL, so total 3 nodes.
  2. Step 2: Count nodes in getLength

    The function counts each node until NULL, so count becomes 3.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    3 nodes counted = 3 [OK]
Hint: Count nodes by following next pointers until NULL [OK]
Common Mistakes:
  • Counting only first node
  • Off-by-one error in loop
  • Confusing data values with count
4. Identify the error in the following code that tries to get the length of a linked list:
int getLength(Node* head) {
  int count = 0;
  while (head->next != NULL) {
    count++;
    head = head->next;
  }
  return count;
}
medium
A. It causes a segmentation fault
B. It misses counting the last node
C. It counts nodes twice
D. It returns the data of the last node

Solution

  1. Step 1: Analyze the loop condition

    The loop runs while head->next != NULL, so it stops before the last node.
  2. Step 2: Check counting logic

    Since last node is not counted, the returned count is one less than actual length.
  3. Final Answer:

    It misses counting the last node -> Option B
  4. Quick Check:

    Loop condition excludes last node [OK]
Hint: Use while(head != NULL) to count all nodes [OK]
Common Mistakes:
  • Using head->next in loop condition
  • Not counting last node
  • Confusing node data with count
5. Given a linked list where each node contains an integer, how would you modify the getLength function to return the length only if all node values are positive? If any node has zero or negative value, return -1.
hard
A. Count nodes normally and ignore values
B. Return -1 if list is empty, else return length
C. Return length only if first node is positive
D. Traverse nodes, if value <= 0 return -1, else count nodes and return count

Solution

  1. Step 1: Traverse each node checking value

    While moving through the list, check if node's data is <= 0; if yes, return -1 immediately.
  2. Step 2: Count nodes if all values positive

    If all nodes have positive values, count them and return the count as length.
  3. Final Answer:

    Traverse nodes, if value <= 0 return -1, else count nodes and return count -> Option D
  4. Quick Check:

    Check values during count, return -1 if any non-positive [OK]
Hint: Check values while counting, stop early if non-positive [OK]
Common Mistakes:
  • Ignoring node values during count
  • Checking only first node value
  • Returning length even if negative values exist
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard