How to Find the Length of a Linked List - The Coding Shala
Home >> Data Structures >> Find the Length of a Linked List
Other Posts You May Like
In this post, we will learn how to find the length of a given linked list in Java.
How to Find the Length of a Linked List
You have given a singly linked list, write a Java program to count the number of elements or length of the linked list.
Example 1:
LinkedList: 1->2->3->4->5
Output: 5
Example 2:
LinkedList: 2->4->6->7->5->1->0
Output: 7
Approach 1
Traverse the linked list until you reached the null node.
Java Program:
/* class Node{ int data; Node next; Node(int a){ data = a; next = null; } }*/ class Solution { public static int getCount(Node head) { int count = 0; Node curr = head; while (curr != null) { count++; curr = curr.next; } return count; } }
- Design Linked List
- Introduction to Graph Data Structure
- Stack Data Structure
- Queue Data Structure
- Introduction to Binary Tree
Comments
Post a Comment