输入两个一元多项式(指数从高到低),自定义项数,系数和指数,用单链表方法顺序输出求乘积后的多项式的各项系数和指数。
2条回答 默认 最新
- threenewbee 2023-03-31 19:38关注
稍等,帮你写一个
#include <stdio.h> #include <stdlib.h> typedef struct node { int coef; int exp; struct node* next; } Node; Node* create_node(int coef, int exp) { Node* new_node = (Node*)malloc(sizeof(Node)); new_node->coef = coef; new_node->exp = exp; new_node->next = NULL; return new_node; } Node* create_poly(int n) { Node* head = NULL; Node* tail = NULL; int coef, exp; for (int i = 0; i < n; i++) { printf("请输入第%d项的系数和指数:", i + 1); scanf("%d%d", &coef, &exp); if (coef != 0) { Node* new_node = create_node(coef, exp); if (head == NULL) { head = new_node; tail = new_node; } else { tail->next = new_node; tail = new_node; } } } return head; } void print_poly(Node* head) { Node* p = head; if (p == NULL) { printf("0\n"); } else { printf("%dx^%d", p->coef, p->exp); p = p->next; while (p != NULL) { printf(" + %dx^%d", p->coef, p->exp); p = p->next; } printf("\n"); } } Node* poly_mult(Node* poly1, Node* poly2) { Node* result = NULL; Node* p1 = poly1; while (p1 != NULL) { Node* p2 = poly2; while (p2 != NULL) { int coef = p1->coef * p2->coef; int exp = p1->exp + p2->exp; Node* q = result; while (q != NULL && q->exp > exp) { q = q->next; } if (q == NULL) { Node* new_node = create_node(coef, exp); new_node->next = result; result = new_node; } else if (q->exp == exp) { q->coef += coef; } else { Node* new_node = create_node(coef, exp); new_node->next = q->next; q->next = new_node; } p2 = p2->next; } p1 = p1->next; } return result; } int main() { int n1, n2; printf("请输入第一个多项式的项数:"); scanf("%d", &n1); Node* poly1 = create_poly(n1); printf("第一个多项式为:"); print_poly(poly1); printf("请输入第二个多项式的项数:"); scanf("%d", &n2); Node* poly2 = create_poly(n2); printf("第二个多项式为:"); print_poly(poly2); Node* result = poly_mult(poly1, poly2); printf("乘积为:"); print_poly(result); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥15 帮我调试idea基于spring boot项目
- ¥15 es 7.17.20版本生成时间戳
- ¥15 wpf dategrid表头排序图标自定义
- ¥15 分析下图所示同步时序逻辑电路的逻辑功能。
- ¥15 halcon联合c#遇到了问题不能解决
- ¥15 xshell无法连接提示ssh服务器拒绝密码
- ¥15 AT89C52单片机C语言关于串口通信的位操作
- ¥20 需要步骤截图(标签-服务器|关键词-map)
- ¥50 gki vendor hook
- ¥15 灰狼算法和蚁群算法如何结合