1 #include <cstdio> 2 #include <stdlib.h> 3 typedef struct Node* Polynomial; 4 struct Node { 5 int coef; 6 int expon; 7 Polynomial next; 8 }; 9 10 void attach(int c, int e, Polynomial *pRear) { 11 Polynomial np = (Polynomial) malloc(sizeof(struct Node)); 12 np->coef = c; 13 np->expon = e; 14 (*pRear)->next = np; 15 *pRear = (*pRear)->next; 16 } 17 int Compare(Polynomial a, Polynomial b) { 18 if(a->expon > b->expon) { 19 return 1; 20 } 21 else if(a->expon < b->expon) { 22 return -1; 23 } 24 else return 0; 25 } 26 27 Polynomial readPoly() { 28 Polynomial head, rear; 29 head = (Polynomial) malloc(sizeof(struct Node)); 30 rear = head; 31 head->next = NULL; 32 33 int n; 34 scanf("%d", &n); 35 for(int i=0; i<n; i++) { 36 int c, e; 37 scanf("%d%d", &c, &e); 38 attach(c, e, &rear); 39 } 40 rear->next = NULL; 41 return head; 42 } 43 44 Polynomial add(Polynomial a, Polynomial b) { 45 Polynomial head, rear; 46 rear = (Polynomial ) malloc(sizeof(struct Node)); 47 head = rear; 48 rear->next = NULL; 49 a = a->next; b = b->next; 50 while(a && b) { 51 switch(Compare(a, b)) { 52 case 1: 53 attach(a->coef, a->expon, &rear); 54 a = a->next; 55 break; 56 case -1: 57 attach(b->coef, b->expon, &rear); 58 b = b->next; 59 break; 60 case 0: 61 int c = a->coef + b->coef; 62 if(c) { 63 attach(c, a->expon, &rear); 64 } 65 a = a->next; 66 b = b->next; 67 break; 68 } 69 } 70 if(a) { 71 rear->next = a; 72 } 73 if(b) { 74 rear->next = b; 75 } 76 77 /* Polynomial temp; 78 temp = head; 79 head = head->next; 80 free(temp); 81 */ 82 return head; 83 84 85 86 } 87 Polynomial multi(Polynomial a, Polynomial b) { 88 Polynomial head, rear, p2 = b->next; 89 rear = (Polynomial ) malloc(sizeof(struct Node)); 90 head = rear; 91 rear->next = NULL; 92 93 a = a->next; b = b->next; 94 while(a) { 95 Polynomial bhead, brear; 96 brear = (Polynomial ) malloc(sizeof(struct Node)); 97 bhead = brear; 98 brear->next = NULL; 99 b = p2; 100 while(b) { 101 attach(a->coef*b->coef, a->expon+b->expon, &brear); 102 b = b->next; 103 } 104 brear->next = NULL; 105 head = add(head, bhead); 106 a = a->next; 107 108 } 109 110 111 return head; 112 113 } 114 115 116 void printPoly(Polynomial a) { 117 int flag = 0; 118 a = a->next; 119 if(!a){ 120 printf("0 0\n"); 121 return; 122 } 123 while(a) { 124 if(!flag) flag = 1; 125 else printf(" "); 126 printf("%d %d", a->coef, a->expon); 127 a = a->next; 128 } 129 printf("\n"); 130 } 131 132 133 134 135 int main (){ 136 Polynomial p1, p2, pp, ps; 137 p1 = readPoly(); 138 p2 = readPoly(); 139 140 ps = add(p1, p2); 141 pp = multi(p1, p2); 142 143 printPoly(pp); 144 printPoly(ps); 145 return 0; 146 }