用C语言实现一元多项式的表示与相加,数据结构
时间: 2024-03-09 13:50:13 浏览: 297
可以使用链表来实现一元多项式的表示和相加,具体实现如下:
1.定义一个结构体来表示一元多项式中的每一项:
```
typedef struct Node {
float coef; // 系数
int exp; // 指数
struct Node *next;
} Node, *Polynomial;
```
2.定义一个函数来创建一元多项式:
```
Polynomial createPoly() {
Polynomial p = (Polynomial)malloc(sizeof(Node));
p->next = NULL;
float coef;
int exp;
printf("请输入一元多项式的系数和指数,以 0 0 结束输入:\n");
scanf("%f %d", &coef, &exp);
while (coef != 0 || exp != 0) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->coef = coef;
newNode->exp = exp;
Node *pre = p;
Node *cur = p->next;
while (cur != NULL && cur->exp > exp) {
pre = cur;
cur = cur->next;
}
newNode->next = cur;
pre->next = newNode;
scanf("%f %d", &coef, &exp);
}
return p;
}
```
3.定义一个函数来输出一元多项式:
```
void printPoly(Polynomial p) {
Node *cur = p->next;
int first = 1;
while (cur != NULL) {
if (first) {
first = 0;
} else {
printf(" + ");
}
printf("%.2f", cur->coef);
if (cur->exp > 0) {
printf("x^%d", cur->exp);
}
cur = cur->next;
}
printf("\n");
}
```
4.定义一个函数来实现一元多项式的相加:
```
Polynomial addPoly(Polynomial p1, Polynomial p2) {
Polynomial sum = (Polynomial)malloc(sizeof(Node));
sum->next = NULL;
Node *cur1 = p1->next;
Node *cur2 = p2->next;
while (cur1 != NULL && cur2 != NULL) {
Node *newNode = (Node *)malloc(sizeof(Node));
if (cur1->exp == cur2->exp) {
newNode->coef = cur1->coef + cur2->coef;
newNode->exp = cur1->exp;
cur1 = cur1->next;
cur2 = cur2->next;
} else if (cur1->exp > cur2->exp) {
newNode->coef = cur1->coef;
newNode->exp = cur1->exp;
cur1 = cur1->next;
} else {
newNode->coef = cur2->coef;
newNode->exp = cur2->exp;
cur2 = cur2->next;
}
Node *pre = sum;
Node *cur = sum->next;
while (cur != NULL && cur->exp > newNode->exp) {
pre = cur;
cur = cur->next;
}
newNode->next = cur;
pre->next = newNode;
}
while (cur1 != NULL) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->coef = cur1->coef;
newNode->exp = cur1->exp;
Node *pre = sum;
Node *cur = sum->next;
while (cur != NULL && cur->exp > newNode->exp) {
pre = cur;
cur = cur->next;
}
newNode->next = cur;
pre->next = newNode;
cur1 = cur1->next;
}
while (cur2 != NULL) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->coef = cur2->coef;
newNode->exp = cur2->exp;
Node *pre = sum;
Node *cur = sum->next;
while (cur != NULL && cur->exp > newNode->exp) {
pre = cur;
cur = cur->next;
}
newNode->next = cur;
pre->next = newNode;
cur2 = cur2->next;
}
return sum;
}
```
使用示例:
```
int main() {
Polynomial p1 = createPoly();
printf("第一个多项式为:");
printPoly(p1);
Polynomial p2 = createPoly();
printf("第二个多项式为:");
printPoly(p2);
Polynomial sum = addPoly(p1, p2);
printf("相加后的多项式为:");
printPoly(sum);
return 0;
}
```
注意:在使用完链表后,需要手动释放链表的内存空间,否则会造成内存泄漏。
阅读全文