I'm working on a linked list where I have to find the average of it's elements using a recursive function. However, I am having problems in two of my functions:
1- If I delete the very first node and then try to check the contents, the list spews garbage data, and if I insert something in the front of the list again, it just endlessly repeats showing the first node contents.
2- I can't seem to figure out how to make the recursive average function work.
Here are the snippets of code for both:
void deletefront(head h) {
head temp; // create a temporary node.
temp = (head)malloc(sizeof(struct node)); // allocate space for node.
temp = h; // transfer the address of 'head' to 'temp'
h = temp->next; // transfer the address of 'temp->next' to 'head'
free(temp);
}
double average2(head h, int sum, int quantity, double avg) {
head temp3;
temp3 = (head)malloc(sizeof(struct node));
temp3 = h;
if (temp3 == NULL) {
cout << "List is Empty" << endl;
return 0;
}
else {
sum = sum + temp3->data;
quantity = quantity + 1;
temp3 = temp3->next;
if (temp3 == NULL) {
return avg = sum / quantity;
}
else return avg = average2(h, sum, quantity, avg);
}
}
And here's the header:
typedef struct node
{
int data; // will store information
node *next; // the reference to the next node
}*head;
Note that I have to make sure that the functions can work with any list.