开发者社区> 问答> 正文

使用列表将C中的多项式相乘

我正在使用列表来实现多项式的乘法。我的代码是:

typedef struct node *node_ptr;
typedef struct node
{
    unsigned int power;
    int coeff;
    node_ptr next;
}POLY;
typedef node_ptr polynomial; 

void mult_polynomial(polynomial poly1, polynomial poly2, polynomial poly_mult)
{
    assert(!is_null(poly1) && !is_null(poly2) && is_null(poly_mult));
    node_ptr p1 = poly1->next;
    node_ptr p2;
    node_ptr p3;
    node_ptr tmp, cell;

    while (p1) {
        p2 = poly2->next;
        while (p2) {
            p3 = poly_mult;
            cell = p3->next;
            tmp = (node_ptr)malloc(sizeof(struct node));
            tmp->power = p1->power + p2->power;
            tmp->coeff = p1->coeff * p2->coeff;
            tmp->next = NULL;
            if (!cell)
                p3->next = tmp;
            else { 
                if (cell->power == tmp->power) {
                    cell->coeff += tmp->coeff;
                    free(tmp);   
                } else if (cell->power < tmp->power) {
                    p3->next = tmp;
                    tmp->next = cell;
                } else if (cell->power > tmp->power) {
                    while (cell->power > tmp->power) {
                        if(!cell->next || cell->next->power < tmp->power) {
                            cell->next = tmp;
                            break; 
                        } else if (cell->next->power == tmp->power) {
                            cell->next->coeff += tmp->coeff;
                            break;
                        }
                        p3 = cell;
                        cell = p3->next;
                    }
                }
            }
            p2 = p2->next;
        }
        p1 = p1->next;
    }
}

但这似乎太多余了;如何简化呢?

展开
收起
游客ufivfoddcd53c 2020-01-04 19:23:57 2583 0
1 条回答
写回答
取消 提交回答
  • 这是我的解决方案。基本上,这是一个完整的重写-尽管所使用的结构仅被重命名,但结构上与您所拥有的等效。

    add_term()事实证明该函数至关重要-它是您所拥有的内容的一部分mult_polynomial(),但是它也适合在add_polynomial()和中使用sub_polynomial()-一个因素表明它是有用的抽象。请注意,mult_polynomial()其结果因此非常简单和紧凑-而且add_polynomial()也不sub_polynomial()复杂。

    2020-01-04 19:24:09
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载