Please write linkedlist.cpp for the following files ----------------------------
ID: 3720123 • Letter: P
Question
Please write linkedlist.cpp for the following files
--------------------------------------------------------------
// linkedlist.h
#ifndef _LINKED_LIST_
#define _LINKED_LIST_
#include <ostream>
class LinkedList
{
public:
LinkedList();
~LinkedList();
void add(int value);
int sum(); // sum of ints in list, calculated iteratively
int sumR(); // sum of ints in list, calculated recursively
friend std::ostream& operator<<(std::ostream& out, LinkedList& list);
private:
struct Node
{
Node(int value) : value(value), next(nullptr) {}
Node(int value, Node* next) : value(value), next(next) {}
int value;
Node* next;
};
int _sumR(Node* node); // sum of ints in list, calculated recursively
Node* head;
};
#endif // _LINKED_LIST_
----------------------------------------
// main.cpp
#include <iostream>
#include "linkedlist.h"
using namespace std;
static const int N_RANDS{9};
int* randomArray(int lgth);
int main()
{
int* ar{randomArray(N_RANDS)};
LinkedList list;
for (int i{0}; i < N_RANDS; i++)
list.add(ar[i]);
cout << "sum() = " << list.sum() << endl;
cout << "sumR() = " << list.sumR() << endl;
delete[] ar;
return 0;
}
Explanation / Answer
//Could you add below methods to your cpp class
recursive version
int sumR(Node *head)
{
if ( head != NULL )
return head->data + Sum(head->next);
else
return 0;
}
iteratively version
int sum(Node *head)
{
int sum = 0;
while (head != NULL) {
sum += head->data;
head = head->next;
}
return sum;
}