顺序表一元多项式指数相加顺序表程序
时间: 2024-06-12 16:09:59 浏览: 68
两个一元多项式相加的程序
5星 · 资源好评率100%
以下是顺序表一元多项式指数相加的程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int coef; // 系数
int expn; // 指数
} ElemType;
typedef struct {
ElemType data[MAXSIZE];
int length;
} SqList;
void InitList(SqList *L) {
L->length = 0;
}
void CreateList(SqList *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 AddList(SqList *La, SqList *Lb, SqList *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;
}
void PrintList(SqList *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");
}
int main() {
SqList La, Lb, Lc;
InitList(&La);
InitList(&Lb);
InitList(&Lc);
CreateList(&La);
CreateList(&Lb);
AddList(&La, &Lb, &Lc);
printf("多项式A:");
PrintList(&La);
printf("多项式B:");
PrintList(&Lb);
printf("多项式C=A+B:");
PrintList(&Lc);
return 0;
}
```
阅读全文