-
Notifications
You must be signed in to change notification settings - Fork 368
/
Copy pathlinklist_length.java
53 lines (53 loc) · 1.53 KB
/
linklist_length.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*Name : Atul Kumar
Github username : atul1510
Repositary name : Algorithms*/
import java.util.Scanner;
// Main class
public class linklist_length
{
public static class Node
{
int data;
Node next;
}
// Function to find the length of a singly linked list
public static int findLength(Node head)
{
int count = 0;
Node current = head;
while (current != null) {
count++;
current = current.next;
}
return count;
}
public static void main(String[] args)
{
// Creating an empty linked list
Node head = null;
// Reading input from the user to create the linked list
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of nodes in the linked list: ");
int n = input.nextInt();
if (n > 0)
{
System.out.print("Enter the data for each node: ");
Node prev = null;
for (int i = 0; i < n; i++) {
Node current = new Node();
current.data = input.nextInt();
current.next = null;
if (prev == null) {
head = current;
} else {
prev.next = current;
}
prev = current;
}
}
// Finding the length of the linked list
int length = findLength(head);
// Printing the length of the linked list
System.out.println("Length of the linked list is: " + length);
}
}