c-将节点添加到指针中,并创建一个列表,然后用于打印多项式



我正在尝试制作一个程序,以这种格式打印多项式,2x^7+1x^2+6x^8。我使用stdarg.h将参数传递到各个节点,然后这些节点将其传递到结构指针中。最后,我将使用一个打印函数,打印出它们最初指向的结构指针中的节点。注意poly-create函数,第一个数字是多项式中的项数,然后它将多项式打印回前面,这意味着当我打印它时,我应该期望1x^7+7x^5+3x^2+3x^4。然而,当我尝试打印它时,我可以打印它通过后的第一个节点,但当我尝试使用for循环打印其余节点时,它给了我一个错误。我希望我的解释不会太糟糕,我已经尽力了,但请问我是否需要澄清一些事情。

.h 的代码

typedef struct nodeT{
  int coef;
  int powr;
  struct nodeT *next;
} node;
typedef struct {
   int num_terms;
   node *terms;
} poly;
void poly_print(poly *P) ; //
poly *poly_create(int num,...) ;

这是我在.c文件中的代码

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "poly_ADT.h"
int main(){
    poly *P0;
    P0 = poly_create(4,3,4,3,2,7,5,1,7); 
    printf("P0: ");
    poly_print(P0);
}
poly *poly_create(int num, ...){
    va_list arguments;
    va_start(arguments, num);
    poly *p = malloc(sizeof(poly));
    p->num_terms = num;
    int i;
    for(i = 0; i < num; i++){
        node *temp = (node* )malloc(sizeof(node* ));
        temp->coef = va_arg(arguments, int);
        temp->powr = va_arg(arguments, int);
        p->terms = temp;
    }
    va_end(arguments);
    return p;
}
void poly_print(poly *P) {
    int x = 0;
    node *n = P->terms;
    //printf("%i terms: ", P->num_terms);
    int i;
    printf("%ix^%i", n->coef, n->powr);
    if (n->next) printf(" + ");
    printf("n");
}
poly *poly_create(int num, ...){
    va_list arguments;
    va_start(arguments, num);
    poly *p = malloc(sizeof(poly));
    p->num_terms = num;
    p->terms = NULL;//! add
    int i;
    for(i = 0; i < num; i++){
        node *temp = (node* )malloc(sizeof(node* ));
        temp->coef = va_arg(arguments, int);
        temp->powr = va_arg(arguments, int);
        temp->next = p->terms;//! add
        p->terms = temp;
    }
    va_end(arguments);
    return p;
}
void poly_print(poly *P) {
    int x = 0;
    node *n = P->terms;
    int i;
    while(n){
        printf("%ix^%i", n->coef, n->powr);
        if (n = n->next) printf(" + ");
    }
    printf("n");
}

最新更新