用链表实现一元多项式相加

能详细解释一下初始化吗
为什么要判断新节点是不是空的?不是已经开辟空间了吗

为什么不能输出呢应该怎么改


#include <stdio.h>
#include <stdlib.h>
//一元多项式相加
typedef struct Node{

int floatcoef; //序数

int intexpn; //指数

struct Node* next;

}Node;



Node* creat(){

Node* head=(Node*)malloc(sizeof(Node));

Node* tail=head;

int coef;//序数
int expn;//指数

scanf("%d %d",&coef,&expn);

while(coef!=0){//////////////////
    Node* node=(Node*)malloc(sizeof(Node));


    if(node!=NULL){///////////
    node->floatcoef=coef;
    node->intexpn=expn;
                    }

    node->next=NULL;
    tail->next=node;
    tail=node;
    scanf("%d %d",&coef,&expn);
}

return head;
}



Node* addpoly(Node* leftpoint,Node* rightpoint){

Node* head1=leftpoint->next;
Node* head2=rightpoint->next;
Node* temp=leftpoint;



while(head1!=NULL&&head2!=NULL){

    if(head1->intexpn<head2->intexpn){

        temp->next=head1;
        head1=head1->next;
        temp=temp->next;
    }
    else if(head2->intexpn<head1->intexpn){
        temp->next=head2->next;
        head2=head2->next;
        temp=temp->next;
    }
    else{
        head1->intexpn+=head2->intexpn;
        temp->next=head1;
        temp=temp->next;
        head1=head1->next;
        head2=head2->next;
    }

}
if(head1!=NULL){
    temp->next=head1;
}
else if(head2!=NULL){
    temp->next=head2;
}
return leftpoint;
}



void print(Node* h){

Node* cur=h->next;

printf("%dx^%d",&cur->floatcoef,&cur->intexpn);

cur=cur->next;

while(cur){
        if(cur->floatcoef==0);
    else{printf("+%dx^%d",cur->floatcoef,cur->intexpn);}
cur=cur->next;
}



}

int main()
{
    Node* a=creat();
        print(a);
    Node* b=creat();

    print(b);
   // Node* c=addpoly(a,b);
    //print(c);
    return 0;
}

因为在用malloc()函数申请结点空间时,有可能会出现不成功的现象,此时malloc() 返回的是个空指针 NULL , 所以为了代码可靠健壮后面加一判断 if(node!=NULL) 确保正确运行。

【相关推荐】




如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^