一元稀疏多项式的加法运算实现c语言代码
时间: 2023-12-25 16:25:46 浏览: 222
一元稀疏多项式的加法运算c语言代码实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int coef; // 系数
int expn; // 指数
} ElemType;
typedef struct {
ElemType data[MAXSIZE];
int length;
} SeqList;
void InitList(SeqList *L) {
L->length = 0;
}
void CreateList(SeqList *L) {
printf("请输入多项式项数:");
scanf("%d", &L->length);
printf("请按照指数从大到小的顺序输入多项式各项的系数和指数:\n");
for (int i = 0; i < L->length; i++) {
scanf("%d%d", &L->data[i].coef, &L->data[i].expn);
}
}
void PrintList(SeqList L) {
for (int i = 0; i < L.length; i++) {
printf("%dx^%d", L.data[i].coef, L.data[i].expn);
if (i != L.length - 1) {
printf("+");
}
}
printf("\n");
}
void AddList(SeqList La, SeqList Lb, SeqList *Lc) {
int i = 0, j = 0, k = 0;
while (i < La.length && j < Lb.length) {
if (La.data[i].expn > Lb.data[j].expn) {
Lc->data[k++] = La.data[i++];
} else if (La.data[i].expn < Lb.data[j].expn) {
Lc->data[k++] = Lb.data[j++];
} else {
int sum = La.data[i].coef + Lb.data[j].coef;
if (sum != 0) {
Lc->data[k].coef = sum;
Lc->data[k++].expn = La.data[i].expn;
}
i++;
j++;
}
}
while (i < La.length) {
Lc->data[k++] = La.data[i++];
}
while (j < Lb.length) {
Lc->data[k++] = Lb.data[j++];
}
Lc->length = k;
}
int main() {
SeqList La, Lb, Lc;
InitList(&La);
InitList(&Lb);
InitList(&Lc);
printf("请输入第一个多项式:\n");
CreateList(&La);
printf("请输入第二个多项式:\n");
CreateList(&Lb);
printf("第一个多项式为:");
PrintList(La);
printf("第二个多项式为:");
PrintList(Lb);
AddList(La, Lb, &Lc);
printf("它们的和为:");
PrintList(Lc);
return 0;
}
```
阅读全文