C语言实现一元多项式加法
#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->exp
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; }
原文地址: https://www.cveoy.top/t/topic/lRHv 著作权归作者所有。请勿转载和采集!