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

typedef struct node{ int coef;//系数 int exp;//指数 struct node* next;//下一项 }node;

node* create(int n) { node* head,p,q; head=(node)malloc(sizeof(node));//创建头结点 head->next=NULL; q=head; int i; for(i=1;i<=n;i++) { p=(node)malloc(sizeof(node)); scanf('%d%d',&p->coef,&p->exp); p->next=NULL; q->next=p; q=p; } return head; }

node* add(node* a,node* b)//将a,b两个多项式相加 { node* head,*p,*q,r; head=(node)malloc(sizeof(node)); head->next=NULL; p=a->next; q=b->next; r=head; while(p!=NULL&&q!=NULL)//将两个多项式相加 { if(p->expexp) { r->next=p; p=p->next; r=r->next; } else if(p->exp>q->exp) { r->next=q; q=q->next; r=r->next; } else { r->next=p; p->coef+=q->coef; q=q->next; p=p->next; r=r->next; } } if(p==NULL)//将剩余的项加到结果多项式中 { r->next=q; } else { r->next=p; } return head; }

void print(node* head)//输出多项式 { node* p; p=head->next; while(p!=NULL) { if(p->coef!=0) { printf('%dx^%d',p->coef,p->exp); if(p->next!=NULL&&p->next->coef>0) { printf('+'); } } p=p->next; } }

int main() { int n,m; node* a,*b,*c; scanf('%d',&n); a=create(n); scanf('%d',&m); b=create(m); c=add(a,b); print(c); return 0; }

C语言实现一元多项式加法

原文地址: https://www.cveoy.top/t/topic/lRHv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录