0

Hi I need to do a recursive function that takes in input the head of a list and sum to each node all the nodes that come after that node. Example if the list is 1->2->3 the list will be modified in 6->5->3. I have done an iterative function that works good but I have no idea of how do a recursive one, can you help? This is the iterative one:

int modify(node *head){

    node **curr;
    node *track = head;
    int i;

    while (track->next != NULL){
        *curr = (track)->next;
        while((*curr)->next != NULL){
            track->val += (*curr)->val;
            *curr = (*curr)->next;
        }
        track = track->next;
    }

    track = head;

    while (track->next != NULL){
        printf("%d ",track->val);
        track = track->next;
    }

    printf("\n");

    return head->val;

}
awwww
  • 23
  • 5

1 Answers1

0
int modify(node *head){
    if(!head) return 0;
    head->val = modify(head->next)+head->val;
    return head->val;
}

If you want to print the values too, you have to use a wrapper function since the recursion runs in reverse order.

void wrapper(node* head){
    modify(head);
    while(head){
        cout<<head->val<<" ";
        head = head->next;
    }
}
Mohit Singh
  • 498
  • 4
  • 10
  • Thanks, how can I modify that list so that once finished prints all the nodes to see if the function is correct? – awwww Feb 13 '20 at 15:07
  • It can be printed in reverse order if that's fine with you. ` cout<val<<" ";` this line before return. – Mohit Singh Feb 13 '20 at 15:18
  • I need the direct order not the reverse one so 1->2->3 becomes 6->5->3, how can I achieve it? – awwww Feb 13 '20 at 15:23