用链表实现多项式的求和问题
设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0
。
输入样例:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例:
15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0
1 #include <stdio.h> 2 3 typedef struct Polynode 4 { 5 int coef; 6 int expp; 7 struct Polynode * next; 8 }Polynode, * Polylist; 9 10 // t表示项数 11 Polylist PolyCreat(int t) 12 { 13 Polynode * head, * rear, *s; 14 int c, e, i = 0; 15 head = (Polynode *)malloc(sizeof(Polynode)); 16 rear = head; 17 while(i < t) 18 { 19 s = (Polynode *)malloc(sizeof(Polynode)); 20 scanf("%d %d", &c, &e); 21 s->coef = c; 22 s->expp = e; 23 rear->next = s; 24 rear = s; 25 i ++; 26 } 27 rear->next = NULL; 28 return head; 29 } 30 31 void Polyprint(Polynode * head) 32 { 33 Polynode * p = head->next; 34 while(p != NULL) 35 { 36 printf("%d %d ", p->coef, p->expp); 37 p = p->next; 38 } 39 } 40 41 // 多项式求和 42 Polylist PolyAdd(Polylist p1, Polylist p2) 43 { 44 Polylist h = PolyCreat(0); 45 Polylist p = p1->next, q = p2->next, tail = h, temp; 46 int sum = 0; 47 while(p != NULL && q != NULL) 48 { 49 if(p->expp > q->expp) //p的指数大于q的指数时,将p结点加入到和多项式 50 { 51 tail->next = p; 52 tail = p; 53 p = p->next; 54 } 55 else if(p->expp == q->expp) 56 { 57 sum = p->coef + q->coef; 58 if(sum != 0) 59 { 60 p->coef = sum; 61 tail->next = p; 62 tail = p; 63 p = p->next; 64 temp = q; 65 q = q->next; 66 free(temp); 67 } 68 else 69 { 70 temp = p; p = p->next; free(p); 71 temp = q; q = q->next; free(q); 72 } 73 } 74 else 75 { 76 tail->next = q; 77 tail = q; 78 q = q->next; 79 } 80 } 81 if(p != NULL) 82 tail->next = p; 83 else 84 tail->next = q; 85 return h; 86 } 87 88 int main(int argc, char const *argv[]) 89 { 90 int a, b; 91 Polylist p1, p2; 92 scanf("%d", &a); 93 p1 = PolyCreat(a); 94 scanf("%d", &b); 95 p2 = PolyCreat(b); 96 Polyprint(p1); 97 puts(" "); 98 Polyprint(p2); 99 puts(" "); 100 Polyprint(PolyAdd(p1, p2)); 101 puts(" "); 102 return 0; 103 }
题目如下,我只实现了多项式的求和问题