如何对链接节点列表执行递归功能

问题描述 投票:0回答:1

嗨,我必须实现一个递归函数,将其输入到列表的开头,然后将所有后面的节点加到每个节点上。 (如果列表为1-> 2-> 3,则必须变为6-> 5-> 3),然后将所有节点加在一起,例如,变量k变为6 + 5 + 3,因此k=14。我无法实现它,您能告诉我如何做到吗?thx

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int val;
    struct node *next;
} node_t;

void somma(node_t *head, int *sum);

int recursive(node_t *head, int *sum);

int main (){

    int max, i, sum=0, sum2=0;

    node_t *head = NULL;
    head = (node_t *)malloc(sizeof(node_t));
    node_t *temp = head;

    printf("Quanti valori vuoi inserire: \n");
    scanf("%d", &max);

    for (i=0; i < max; i++){
        temp->next = (node_t *)malloc(sizeof(node_t));
        printf("Inserisci il valore in posizione %d\n", i);
        scanf("%d", &temp->val);
        temp = temp->next;
        temp->next = NULL;
    }

    somma(head, &sum);

    printf("La somma e' %d\n", sum);

    recursive(head, &sum2);

    printf("La somma calcolata rec e': %d\n", sum2);

    return 0;
}

void somma(node_t *head, int *sum){

    node_t *curr = head;
    node_t *start = head;

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

    start = head;

    while (start->next != NULL){
        (*sum) += start->val;
        start = start->next;
    }

    return ;
}
c99
1个回答
0
投票

那些应该起作用。

© www.soinside.com 2019 - 2024. All rights reserved.