-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount_nodes.cpp
80 lines (68 loc) · 1.14 KB
/
count_nodes.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include<iostream>
#include<cmath>
using namespace std;
class Node{
public:
int data;
Node *next;
}*first=NULL;
void create(int a[],int n){
int i;
Node *t,*last;
first=new Node();
first->data = a[0];
first->next = NULL;
last=first;
for(i=1;i<n;i++){
t = new Node();
t->data = a[i];
t->next = NULL;
last->next=t;
last=t;
}
}
int count(Node *p){
int c=0;
while(p){
c++;
p=p->next;
}
return c;
}
int rec_count(Node *p){
if(p==NULL)
return 0;
else
return count(p->next) +1;
}
int add(Node *p){
int sum=0;
while(p!=0){
sum += p->data;
p=p->next;
}
return sum;
}
void middle_1(Node *p){
Node *q = p;
while (q){
q = q->next;
if (q){
q = q->next;
}
if (q){
p = p->next;
}
}
cout << "Middle Element (Method-II): " << p->data << endl;
}
int main(){
int a[] = {8,18,28,12,4};
create(a,5);
// rec_display(first);
cout<<"Count: "<<count(first);
cout<<"Recursive Count: "<<rec_count(first);
cout<<"Sum is: "<<add(first);
middle_1(first);
return 0;
}