DDSA Solutions

Count Linked List Nodes

Time: O(n)
Space: O(1)
Advertisement

Intuition

Count total number of nodes in a linked list.

Algorithm

  1. 1Traverse from head, increment counter at each node until null.

Common Pitfalls

  • Simple O(n) traversal. Edge case: empty list returns 0.
Count Linked List Nodes.java
Java
// Approach: Traverse the list and increment a counter for each node.
// Time: O(n) Space: O(1)
class Solution {
    // Function to count nodes of a linked list.
    public int getCount(Node head) {
        Node curr = head;
        int cnt = 0;

        while (curr != null) {
            cnt += 1;
            curr = curr.next;
        }

        return cnt;
    }
}

class Node {
    int data;
    Node next;

    Node(int a) {
        data = a;
        next = null;
    }
}
Advertisement
Was this solution helpful?