建立一元多项式单链表时,根据输入值来确定结束构建单链表, 编写一元多项式的相加程序,要编写多项式单链表的输出函数,以便能验证程序的执行结果的C语言代码和注释
时间: 2024-05-08 19:15:21 浏览: 85
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
float coef; // 系数
int expn; // 指数
struct node *next; // 指向下一个节点的指针
} Node, *Polynomial;
// 创建多项式单链表
void createPoly(Polynomial *p) {
*p = NULL; // 初始化为空链表
Node *tail = *p; // 定义尾指针
float c; // 系数
int e; // 指数
printf("请输入多项式的系数和指数(以0 0结束):\n");
while (1) {
scanf("%f%d", &c, &e);
if (c == 0 && e == 0) {
break; // 输入0 0时结束
}
Node *newNode = (Node *)malloc(sizeof(Node)); // 动态分配一个新节点
newNode->coef = c;
newNode->expn = e;
newNode->next = NULL;
if (*p == NULL) {
*p = newNode; // 第一个节点
} else {
tail->next = newNode;
}
tail = newNode; // 将尾指针指向新节点
}
}
// 输出多项式单链表
void printPoly(Polynomial p) {
if (p == NULL) {
printf("多项式为空!\n");
} else {
printf("多项式为:");
while (p != NULL) {
if (p->expn == 0) {
printf("%.1f", p->coef);
} else if (p->expn == 1) {
printf("%.1fx", p->coef);
} else {
printf("%.1fx^%d", p->coef, p->expn);
}
p = p->next;
if (p != NULL) {
printf(" + ");
}
}
printf("\n");
}
}
// 多项式相加
Polynomial addPoly(Polynomial p1, Polynomial p2) {
Node *tail; // 新链表尾指针
Node *temp; // 临时节点指针
Polynomial p3 = NULL; // 新链表头指针
tail = p3;
while (p1 != NULL && p2 != NULL) {
if (p1->expn == p2->expn) { // 指数相同
float sum = p1->coef + p2->coef;
if (sum != 0) { // 系数和不为0
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->coef = sum;
newNode->expn = p1->expn;
newNode->next = NULL;
if (p3 == NULL) {
p3 = newNode;
} else {
tail->next = newNode;
}
tail = newNode;
}
p1 = p1->next;
p2 = p2->next;
} else if (p1->expn > p2->expn) { // p1的指数大于p2的指数
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->coef = p1->coef;
newNode->expn = p1->expn;
newNode->next = NULL;
if (p3 == NULL) {
p3 = newNode;
} else {
tail->next = newNode;
}
tail = newNode;
p1 = p1->next;
} else { // p2的指数大于p1的指数
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->coef = p2->coef;
newNode->expn = p2->expn;
newNode->next = NULL;
if (p3 == NULL) {
p3 = newNode;
} else {
tail->next = newNode;
}
tail = newNode;
p2 = p2->next;
}
}
// 将剩余的节点加入新链表
if (p1 != NULL) {
temp = p1;
} else {
temp = p2;
}
while (temp != NULL) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->coef = temp->coef;
newNode->expn = temp->expn;
newNode->next = NULL;
if (p3 == NULL) {
p3 = newNode;
} else {
tail->next = newNode;
}
tail = newNode;
temp = temp->next;
}
return p3;
}
int main() {
Polynomial p1, p2, p3;
printf("请输入第一个多项式:\n");
createPoly(&p1);
printPoly(p1);
printf("请输入第二个多项式:\n");
createPoly(&p2);
printPoly(p2);
p3 = addPoly(p1, p2);
printf("两个多项式相加的结果为:\n");
printPoly(p3);
return 0;
}
```
阅读全文