1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| #include<stdio.h> #include<stdlib.h> struct node { float coef; int expn; struct node *next; }; typedef struct node *linklist;
void CreatPolyn(linklist p, int m) { int i; linklist head = p; head->coef = 0.0; head->expn = -1; head->next = NULL; p = head; for (i = 0; i<m; i++) { p = p->next = (linklist)malloc(sizeof(struct node)); scanf("%f%d", &p->coef, &p->expn); } p->next = NULL; } int cmp(int p, int q) { if (p < q) return -1; else if(q == p) return 0; else return 1; } void Append(linklist p, linklist qa) { while (p->next != NULL) { p = p->next; if (p->next == NULL) { p->next = qa; break; } } } void AddPolyn(linklist p, linklist q) { float sum = 0; linklist ha = p,hb = q,temp = NULL; linklist pa = p->next; linklist qa = q->next; while (pa && qa) { switch (cmp(pa->expn, qa->expn)) { case -1: pa = pa->next; ha = ha->next; break; case 0: sum = pa->coef + qa->coef; if (sum != 0) { pa->coef = sum; } else { temp = pa->next; free(ha->next); ha->next = temp; pa = ha->next; } temp = qa->next; free(qa); qa = temp; if(pa->next != NULL) pa = pa->next; break; case 1: temp = qa->next; ha->next = qa; qa->next = pa; ha = ha->next; qa = temp; break; } } if (qa != NULL) { Append(p, qa); } free(temp); free(hb); }
int main(void) { int n, m; linklist p = (linklist)malloc(sizeof(struct node)); linklist q = (linklist)malloc(sizeof(struct node)); printf("格式:<系数,指数>\n"); printf("请输入第一个多项式的项数:"); scanf("%d", &n); CreatPolyn(p, n); printf("请输入第二个多项式的项数:"); scanf("%d", &m); CreatPolyn(q, m); AddPolyn(p, q); printf("两个多项式的和为:\n"); p = p->next; while (p != NULL) { printf("<%f,%d> ", p->coef, p->expn); p = p->next; } return 0; }
|