编写一个c语言程序用单链表储存一元多项式,并实现两个多项式相加的运算
时间: 2024-02-11 18:12:59 浏览: 27
好的,以下是一个基于单链表储存一元多项式的C语言程序,并实现了两个多项式相加的运算:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式结构体
typedef struct PolyNode {
int coef; // 系数
int expon; // 指数
struct PolyNode* next; // 指向下一个结点的指针
} PolyNode, *Polynomial;
// 创建一个空的多项式
Polynomial CreatePoly() {
Polynomial P = (Polynomial)malloc(sizeof(PolyNode));
if (!P) {
printf("内存分配失败!\n");
exit(1);
}
P->next = NULL;
return P;
}
// 释放多项式所占用的内存
void DestroyPoly(Polynomial P) {
Polynomial temp;
while (P) {
temp = P;
P = P->next;
free(temp);
}
}
// 将项插入多项式
void InsertItem(Polynomial P, int coef, int expon) {
Polynomial temp, pre, newnode;
pre = P;
temp = pre->next;
while (temp && temp->expon > expon) {
pre = temp;
temp = pre->next;
}
if (temp && temp->expon == expon) {
temp->coef += coef;
if (temp->coef == 0) {
pre->next = temp->next;
free(temp);
}
} else {
newnode = (Polynomial)malloc(sizeof(PolyNode));
if (!newnode) {
printf("内存分配失败!\n");
exit(1);
}
newnode->coef = coef;
newnode->expon = expon;
newnode->next = temp;
pre->next = newnode;
}
}
// 读入多项式
Polynomial ReadPoly() {
Polynomial P = CreatePoly();
int n, coef, expon;
scanf("%d", &n);
while (n--) {
scanf("%d %d", &coef, &expon);
InsertItem(P, coef, expon);
}
return P;
}
// 求两个多项式的和
Polynomial AddPoly(Polynomial P1, Polynomial P2) {
Polynomial P = CreatePoly();
Polynomial temp1 = P1->next, temp2 = P2->next;
while (temp1 && temp2) {
if (temp1->expon > temp2->expon) {
InsertItem(P, temp1->coef, temp1->expon);
temp1 = temp1->next;
} else if (temp1->expon < temp2->expon) {
InsertItem(P, temp2->coef, temp2->expon);
temp2 = temp2->next;
} else {
InsertItem(P, temp1->coef + temp2->coef, temp1->expon);
temp1 = temp1->next;
temp2 = temp2->next;
}
}
while (temp1) {
InsertItem(P, temp1->coef, temp1->expon);
temp1 = temp1->next;
}
while (temp2) {
InsertItem(P, temp2->coef, temp2->expon);
temp2 = temp2->next;
}
return P;
}
// 输出多项式
void PrintPoly(Polynomial P) {
Polynomial temp = P->next;
int flag = 0; // 标记是否为第一项
if (!temp) {
printf("0 0\n");
return;
}
while (temp) {
if (!flag) {
flag = 1;
} else {
printf(" ");
}
printf("%d %d", temp->coef, temp->expon);
temp = temp->next;
}
printf("\n");
}
int main() {
Polynomial P1, P2, P;
P1 = ReadPoly();
P2 = ReadPoly();
P = AddPoly(P1, P2);
PrintPoly(P);
DestroyPoly(P1);
DestroyPoly(P2);
DestroyPoly(P);
return 0;
}
```
上述程序中,我们定义了一个多项式结构体,并实现了创建一个空的多项式、将项插入多项式、读入多项式、释放多项式、求两个多项式的和、输出多项式等基本操作。在主函数中,我们读入两个多项式,并通过AddPoly函数求它们的和,最后输出结果并释放内存。