Skip to content

Commit 3fcce41

Browse files
authored
Merge pull request #117 from shikhar8434/master
Added Count the Nodes of a linked list problem
2 parents 41a16db + 4588157 commit 3fcce41

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

data_structures/C++/CountNodes.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
struct Node{
5+
int data;
6+
struct Node *next;
7+
8+
Node(int x){
9+
data=x;
10+
next=NULL;
11+
}
12+
};
13+
14+
int CountElements(Node *head){
15+
16+
int count=0;
17+
18+
struct Node *curr= head;
19+
while(curr!=NULL){
20+
curr=curr->next;
21+
count++;
22+
}
23+
return count;
24+
}
25+
26+
int main()
27+
{
28+
int data,n;
29+
cin>>n;
30+
cin>>data;
31+
struct Node *head= new Node(data);
32+
struct Node *tail= head;
33+
for(int i=0;i<n-1;i++){
34+
cin>>data;
35+
tail->next=new Node(data);
36+
tail=tail->next;
37+
}
38+
cout<<CountElements(head)<<endl;
39+
return 0;
40+
41+
}

0 commit comments

Comments
 (0)