700039. Count Linked List Nodes
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:
- Initialize a variable
countto 0. - Start from the head of the linked list (node).
- For each node in the linked list, increment the
countby 1 and move to the next node. - Continue this process until you reach the end of the linked list.
- 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
public int countNodes(ListNode head) {
int count = 0;
ListNode current = head;
while (current != null) {
count++;
current = current.next;
}
return count;
}