时间:2021-04-19 08:04:55 | 栏目:C代码 | 点击:次
本文实例为大家分享了C语言多项式相加的具体代码,供大家参考,具体内容如下
包含带头节点的链表的初始化,输出:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> typedef struct Pol { int coe; // 系数 int index; // 指数 struct Pol *next; }Pol; int main(int argc, char *argv[]) { Pol *head1 = NULL; // 第一个多项式 Pol *head2 = NULL; // 第二个多项式 Pol *Initiate(Pol *head1); // 声明初始化函数 void Output(Pol *head); // 声明输出函数 void PolAdd(Pol *head1, Pol *head2); // 声明相加函数 int coe, index; char sign; Pol *p; int n = 0; // 初始化第一个多项式 head1 = Initiate(head1); p = head1; while (1) { scanf("%dx%d%c", &coe, &index, &sign); p->next = (Pol *)malloc(sizeof(Pol)); p = p->next; p->coe = coe; p->index = index; p->next = NULL; if(sign == '\n') break; } printf("第一多项式输入完毕。\n"); // 初始化第二个多项式 head2 = Initiate(head2); p = head2; while (1) { scanf("%dx%d%c", &coe, &index, &sign); p->next = (Pol *)malloc(sizeof(Pol)); p = p->next; p->coe = coe; p->index = index; p->next = NULL; if (sign == '\n') break; } printf("第二多项式输入完毕。\n"); // 调用相加函数和输出函数 PolAdd(head1, head2); Output(head1); system("PAUSE"); return 0; } // 初始化链表函数 Pol *Initiate(Pol *head) { head = (Pol *)malloc(sizeof(Pol)); head->next = NULL; return head; } // 初始化相加函数 void PolAdd(Pol *head1, Pol *head2) { Pol *p = head1->next; Pol *q = head2->next; Pol *pre = head1; Pol *temp = NULL; int sum; while ((p != NULL) && (q != NULL)) { if (p->index < q->index) { pre->next = p; pre = pre->next; p = p->next; } else if(p->index == q->index) { sum = p->coe + q->coe; if (sum != 0) { p->coe = sum; pre->next = p; pre = pre->next; p = p->next; // 删除节点 temp = q; q = q->next; free(temp); } else { temp = p; p = p->next; free(temp); temp = q; q = q->next; free(temp); } } else { pre->next = q; pre = pre->next; q = q->next; } } // 两串长度不相等时,把尾部一次加入 if (p != NULL) pre->next = p; else pre->next = q; } // 输出函数 void Output(Pol *head) { Pol *p = head; p = p->next; int i = 0; while (p) { if (p->coe > 0 && i != 0) { printf("+%dX^%d", p->coe, p->index); p = p->next; } else { printf("%dX^%d", p->coe, p->index); p = p->next; } i++; } }