今天来个应用—— 一元多项式相加 代码如下:
//一元多项式相加
//2012-12-16
//@quanwei
#include<stdio.h>
#include<stdlib.h>
typedef struct polynomial{
double coef;
int expn;
struct polynomial *pNext;
}POLYN;
POLYN *CreatPolyn();
POLYN *AddPolyn(POLYN *head1,POLYN *head2);
void DisplayPolyn(POLYN *head);
void main(){
POLYN *head1,*head2;
int n;
printf("创建多项式1\n");
head1 = CreatPolyn();
printf("创建多项式2\n");
head2 = CreatPolyn();
head1=AddPolyn(head1,head2);
DisplayPolyn(head1);
}
/******************************/
//函数名: CreatPolyn()
//参数: 无
//功能: 创建一个带头结点的n+1元链表,存放n项一元多项式
//返回值: 一元多项式头指针
/******************************/
POLYN *CreatPolyn(){
POLYN *head,*pNew,*pWork;
head = (POLYN *)malloc(sizeof(POLYN)); //创建头结点
pWork = head;
int n;
printf("输入多项式项数:\n");
scanf("%d",&n);
for(int i = 0;i < n;i++){
pNew = (POLYN *)malloc(sizeof(POLYN));
printf("输入系数和指数");
scanf("%lf %d",&pNew->coef,&pNew->expn);
pWork->pNext = pNew;
pWork = pNew;
}
pWork->pNext = NULL; //尾为空pWork->pNext = NULL,不是pWork = NULL
return head;
}
/******************************/
//函数名: AddPolyn(POLYN *head1,POLYN *head2)
//参数: POLYN *head1 多项式1头指针
// POLYN *head2 多项式2头指针
//功能: 将两多项式相加,并将结果存于一新的线性表中
//返回值: 相加后存储多项式的线性表的头指针
/******************************/
POLYN *AddPolyn(POLYN *head1,POLYN *head2){
POLYN *pa = head1->pNext,*pb = head2->pNext,*pWork;
POLYN *head3 = (POLYN *)malloc(sizeof(POLYN));
pWork = head3;
while(pa != NULL && pb != NULL){
if(pa->expn > pb->expn){
pWork->pNext = pb;
pWork = pWork->pNext;
pb = pb->pNext;
}else if(pa->expn < pb->expn){
pWork->pNext = pa;
pWork = pWork->pNext;
pa = pa->pNext;
}else{
POLYN *pTemp = (POLYN *)malloc(sizeof(POLYN)); //分配存储空间,存放两项的和
pTemp->coef = pa->coef + pa->coef;
pTemp->expn = pa->expn + pa->expn;
if(pTemp->coef){
pWork->pNext = pTemp;
pWork = pWork->pNext;
pa = pa->pNext;
pb = pb->pNext;
}
}
}
(pa == NULL) ? (pWork ->pNext = pb):(pWork ->pNext = pa);
return head3;
}
/******************************/
//函数名: DisplayPolyn(POLYN *head)
//参数: POLYN *head1 多项式头指针
//功能: 显示多项式
//返回值: 无
/******************************/
void DisplayPolyn(POLYN *head){
POLYN *pWork = head->pNext;
while(pWork != NULL){
printf("%lf(%d)",pWork->coef,pWork->expn);
pWork = pWork->pNext;
}
}
其实还可以写个集合运算,但是。。。。懒得写了