递归计算两个列表之间的乘积(带条件)

Recursively calculate the product between two lists (with condition)

练习要求我获得两个列表的乘积,前提是节点的总和与列表中的位置相比处于多个位置。因此,如果此 ((l1->d + l2->d) % pos == 0)) 为真,则构建一个新列表。我做了我的尝试,但我不明白为什么它是错误的。我错过了什么?

Nodo *prodotto_pos(Nodo *l1, Nodo *l2, int pos)
{
    Nodo *p;

    if ((l1 == NULL) && (l2 == NULL)) return NULL;
    else if ((l1 != NULL) && (l2 != NULL))
    {
        if (((l1->d + l2->d) % pos) == 0)
        {
            p = newnode();
            p->d = ((l1->d) * (l2->d));
            p->next = prodotto_pos(l1->next, l2->next, pos+1);
        }
    }
    return p;
}

示例:

L1: 3->4->2->7->5->6->11->16->7->2->NULL

L2: 0->2->2->6->2->12->2->NULL

输出:0->8->72->NULL

问题是如果 product 错误并且你从函数 return 中你不递归调用函数 突然。

检查下面的 else 块。

if (((l1->d + l2->d) % pos) == 0)
{
    p = newnode();
    p->d = ((l1->d) * (l2->d));
    p->next = prodotto_pos(l1->next, l2->next, pos+1);
}
else
{
   p = prodotto_pos(l1->next, l2->next, pos+1);
}

给你。

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

typedef struct Nodo
{
    int d;
    struct Nodo *next;
} Nodo;

int push_front( Nodo **head, int value )
{
    Nodo *tmp = malloc( sizeof( Nodo ) );
    int success = tmp != NULL;

    if ( success )
    {
        tmp->d = value;
        tmp->next = *head;
        *head = tmp;
    }

    return success;
}

Nodo * prodotto_pos( const Nodo *first, const Nodo *second )
{
    static int pos = 0;

    Nodo *current = NULL;

    if ( first != NULL && second != NULL )
    {
        ++pos;

        if ( ( first->d + second->d ) % pos == 0 )
        {
            current = malloc( sizeof( Nodo ) );
            current->d = first->d * second->d;
            current->next = prodotto_pos( first->next, second->next );
        }
        else
        {
            current = prodotto_pos( first->next, second->next );
        }

        --pos;
    }

    return current;
}

void display( const Nodo *head )
{
    for ( ; head != NULL; head = head->next )
    {
        printf( "%d -> ", head->d );
    }

    puts( "NULL" );
}

int main( void )
{
    Nodo *first = NULL;
    Nodo *second = NULL;

    int a1[] = { 3, 4, 2, 7, 5, 6, 11, 16, 7, 2 };
    const size_t N1 = sizeof( a1 ) / sizeof( *a1 );

    int a2[] = { 0, 2, 2, 6, 2, 12, 2 };
    const size_t N2 = sizeof( a2 ) / sizeof( *a2 );

    for ( size_t i = N1; i != 0; --i )
    {
        push_front( &first, a1[i-1] );
    }

    for ( size_t i = N2; i != 0; --i )
    {
        push_front( &second, a2[i-1] );
    }

    display( first );
    display( second );

    Nodo *product = prodotto_pos( first, second );

    display ( product );
}

程序输出为

3 -> 4 -> 2 -> 7 -> 5 -> 6 -> 11 -> 16 -> 7 -> 2 -> NULL
0 -> 2 -> 2 -> 6 -> 2 -> 12 -> 2 -> NULL
0 -> 8 -> 72 -> NULL