700039. Count Linked List Nodes

Basic

Count Linked List Nodes

Slug: count-nodes-of-linked-list Difficulty: Basic Id: 700039 Topic Tags: Linked List, Data Structures Company Tags: None

Summary

Counting nodes in a linked list is a fundamental algorithmic problem that requires traversing the linked list and keeping track of the number of nodes. This problem involves working with data structures and algorithms to solve the issue.

Detailed Explanation

To count the nodes in a linked list, we can traverse the linked list and increment a counter for each node. The basic idea is to start from the head of the linked list and move towards the end. At each step, we increment the count and move to the next node until we reach the end of the linked list.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable count to 0.
  2. Start from the head of the linked list (node).
  3. For each node in the linked list, increment the count by 1 and move to the next node.
  4. Continue this process until you reach the end of the linked list.
  5. Return the final count.

Time complexity: O(n), where n is the number of nodes in the linked list. Space complexity: O(1), as we only use a constant amount of space to store the count variable.

Optimized Solutions

Java

View on GeeksforGeeks
public int countNodes(ListNode head) {
    int count = 0;
    ListNode current = head;
    while (current != null) {
        count++;
        current = current.next;
    }
    return count;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.