-
Notifications
You must be signed in to change notification settings - Fork 369
/
Copy pathlinklist_length.c
52 lines (52 loc) · 1.33 KB
/
linklist_length.c
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
/*Name : Atul Kumar
Github username : atul1510
Repositary name : Algorithms*/
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
struct Node* next;
};
// Function to find the length of a singly linked list
int findLength(struct Node* head)
{
int count = 0;
struct Node* current = head;
while (current != NULL)
{
count++;
current = current->next;
}
return count;
}
int main()
{
// Creating an empty linked list
struct Node* head = NULL;
// Reading input from the user to create the linked list
printf("Enter the number of nodes in the linked list: ");
int n;
scanf("%d", &n);
if (n > 0)
{
printf("Enter the data for each node: ");
struct Node* prev = NULL;
for (int i = 0; i < n; i++) {
struct Node* current = (struct Node*) malloc(sizeof(struct Node));
scanf("%d", ¤t->data);
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
printf("Length of the linked list is: %d\n", length);
return 0;
}