#include
#include

//poly数据类型
typedef struct poly
{
int coef;
int expn;
struct poly *pnext;
} POLY;

//初始化表达式
POLY *InitPoly(void)
{
if ((phead = (POLY *)malloc(sizeof(POLY))) == NULL)
exit(-1);
}

//输入表达式
{
int coef,expn;
POLY *ptail,*pnew;
while(1)
{
scanf("%d,%d", &coef, &expn);
if (coef != 0)
{
if ((pnew = (POLY *)malloc(sizeof(POLY))) == NULL)
exit(-1);
pnew->coef = coef;
pnew->expn = expn;
ptail->pnext = pnew;
ptail = pnew;
}
else
{
break;
}
}

``````ptail->pnext = NULL;
``````

}

//输出表达式
{
POLY *ptemp;

``````if (ptemp == NULL)
{
printf("\n");
return;
}
printf("%dx^%d", ptemp->coef, ptemp->expn);
ptemp = ptemp->pnext;

while(ptemp != NULL)
{
printf("+%dx^%d", ptemp->coef, ptemp->expn);
ptemp = ptemp->pnext;
}
printf("\n");
``````

}

//表达式相加
{
int temp;
POLY *ptempA, *ptempB; //运算链表相关变量

``````ptempA = pheadA->pnext;

//将两个多项式扫描运算后放入结果链表中
while(ptempA != NULL && ptempB != NULL)
{
//如果指数相等
if (ptempA->expn == ptempB->expn)
{

if ((temp = ptempA->coef + ptempB->coef) == 0)
{
ptempA = ptempA->pnext;
ptempB = ptempB->pnext;
continue;
}
if ((pnew = (POLY *)malloc(sizeof(POLY))) == NULL)
exit(-1);
pnew->coef = temp;
pnew->expn = ptempA->expn;
ptail->pnext = pnew;
pnew->pnext = NULL;
ptail = pnew;
ptempA = ptempA->pnext;
ptempB = ptempB->pnext;

}//如果多项式A指数小于B
else if(ptempA->expn < ptempB->expn)
{
if ((pnew = (POLY *)malloc(sizeof(POLY))) == NULL)
exit(-1);
*pnew = *ptempA;
pnew->pnext = NULL;
ptail->pnext = pnew;
ptail = pnew;
ptempA = ptempA->pnext;
}//如果多项式A指数大于B
else
{
if ((pnew = (POLY *)malloc(sizeof(POLY))) == NULL)
exit(-1);
*pnew = *ptempB;
pnew->pnext = NULL;
ptail->pnext = pnew;
ptail = pnew;
ptempB = ptempB->pnext;
}
}
//将剩余的未扫描项放入结果链表中
while(ptempA != NULL)
{
if ((pnew = (POLY *)malloc(sizeof(POLY))) == NULL)
exit(-1);
*pnew = *ptempA;
pnew->pnext = NULL;
ptail->pnext = pnew;
ptail = pnew;
ptempA = ptempA->pnext;
}
while(ptempB != NULL)
{
if ((pnew = (POLY *)malloc(sizeof(POLY))) == NULL)
exit(-1);
*pnew = *ptempB;
pnew->pnext = NULL;
ptail->pnext = pnew;
ptail = pnew;
ptempB = ptempB->pnext;
}
``````

}

//多项式求导
{
while(ptemp != NULL)
{
if (ptemp->expn == 0)
{
ptemp = ptemp->pnext;
continue;
}
if ((pnew = (POLY *)malloc(sizeof(POLY))) == NULL)
exit(-1);
pnew->coef = ptemp->coef * ptemp->expn;
pnew->expn = ptemp->expn - 1;
ptail->pnext = pnew;
pnew->pnext = NULL;
ptail = pnew;
ptemp = ptemp->pnext;
}
}

int main(void)
{
printf("请输入多项式A(系数,指数),需指数递增输入,系数为0时结束输入:\n");

``````pheadB = InitPoly();
printf("请输入多项式B(系数,指数),需指数递增输入,系数为0时结束输入:\n");

printf("多项式A：");
printf("多项式B：");

printf("多项式A + 多项式B = ");
OutputPoly(result);

printf("多项式A求导 = ");
OutputPoly(result);

printf("多项式B求导 = ");
OutputPoly(result);

return 0;
``````

}

1个回答