-
Notifications
You must be signed in to change notification settings - Fork 368
/
linklist_length.cpp
51 lines (51 loc) · 1.24 KB
/
linklist_length.cpp
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
/*Name : Atul Kumar
Github username : atul1510
Repositary name : Algorithms*/
#include <iostream>
using namespace std;
// Node structure
struct Node {
int data;
Node* next;
};
// Function to find the length of a singly linked list
int findLength(Node* head)
{
int count = 0;
Node* current = head;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
int main()
{
// Creating an empty linked list
Node* head = NULL;
// Reading input from the user to create the linked list
cout << "Enter the number of nodes in the linked list: ";
int n;
cin >> n;
if (n > 0)
{
cout << "Enter the data for each node: ";
Node* prev = NULL;
for (int i = 0; i < n; i++) {
Node* current = new Node;
cin >> current->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
cout << "Length of the linked list is: " << length << endl;
return 0;
}