-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpp-data-structures-linked-lists-count-sum.cpp
100 lines (71 loc) · 1.32 KB
/
cpp-data-structures-linked-lists-count-sum.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <iostream>
using namespace std;
struct Node {
int data; // data member
struct Node* next; // self-referencial member pointer
}
*first = NULL;
void create(int A[], int n) // creating a linked list from an array
{
int i;
struct 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(struct Node* p) // count a linked list
{
int count = 0;
while (p)
{
count++;
p = p->next;
}
return count;
}
int Rcount(struct Node* p) // count a linked list recursively
{
if (p == 0)
{
return 0;
}
else
return Rcount(p->next) + 1;
}
int sumList(struct Node* p) // sum the data in all the nodes
{
int sum = 0;
while (p)
{
sum = sum + p->data;
p = p->next;
}
return sum;
}
int RsumList(struct Node* p) // sum all node data using recursion
{
if (p == 0)
{
return 0;
}
else
return RsumList(p->next) + p->data;
}
int main() {
int A[] = { 3,5,7,10,15 };
create(A, 5);
cout << "Length is " << count(first) << endl;
cout << "Length is " << Rcount(first) << endl;
cout << "Sum is " << sumList(first) << endl;
cout << "Sum is " << RsumList(first) << endl;
return 0;
}