I am trying to make a function that recursively adds up the data areas of a linked list and finds the sum of all the cells added together. I put the class together but it does not like how I am declaring my list in the main.
#include <iomanip>
#include <iostream>
usingnamespace std;
struct node
{
int data;
node* next;
};
class Link
{
private:
/* struct node
{
int data;
node* next;
};
*/
node *head;
public:
Link();
int sum(node *head);
void push(int item);
};
int main(){
// Find the sum of the inputted numbers
int Link z;
z.push(1);
z.push(4);
z.push(2);
z.push(3);
cout << "Should equal 10" << endl;
cout << z.sum() << endl;
return 0;
}
Link :: Link()
{
}
void Link :: push(int item)
{
node *t = new node;
t -> data = item;
t -> next = head;
head = t;
}
int Link :: sum (node *head)
{
if(head == NULL)
return 0;
elsereturn head ->data + sum(head ->next);
}
Line 32 should be Link z;.
Your sum() takes a node* as a parameter so line 39 cout << z.sum() << endl; won't work.
I modified your code a bit and got it to work. Unfortunately head is no longer private here since it must be supplied as an argument to sum(). Can you think of a better way to make this work (so that head can remain private)?
I think your constructor ought to initialize head = NULL since the list is empty.
I also changed the node* used in sum() to pNode from head because head is just the starting value. You don't want to be changing the value of head in the sum().
Nice job on the recursive function! It works fine. I get 10 for the sum.
thank you for your help guys ima take what you all did into consideration and even use what u said fun2code thanks allot for taking the time to run it your self im gana fix it right now :)