两个一元多项式相加
Posted 一个拿着底层薪资操着架构师的心的码农
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了两个一元多项式相加相关的知识,希望对你有一定的参考价值。
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 struct PolyNode { 5 int coefficient; //系数 6 int exponent; //指数 7 struct PolyNode* next; 8 }; 9 10 typedef struct PolyNode *Polynomial; 11 Polynomial p1, p2; 12 13 //初始化一元多项式链表 14 void InitPolynomial(Polynomial *p); 15 // 将比较之后的项插入到新链的尾部 16 void Attach(int c, int e, Polynomial* pRear); 17 //比较两项指数的大小 18 int Compare(int exponent1, int exponent2); 19 //比较两个多项式的各项,依次插入到新项 20 Polynomial PolyAdd(Polynomial P1, Polynomial P2); 21 //打印链表的值 22 void printPolynomial(Polynomial P); 23 24 int main() 25 { 26 InitPolynomial(&p1); 27 InitPolynomial(&p2); 28 Polynomial p3 = PolyAdd(p1, p2); 29 printPolynomial(p1); 30 printPolynomial(p2); 31 printPolynomial(p3); 32 33 return 0; 34 } 35 36 37 //初始化一元多项式链表 38 void InitPolynomial(Polynomial *p) //二级指针 39 { 40 41 (*p) = (Polynomial)malloc(sizeof(struct PolyNode)); 42 Polynomial head = *p; 43 int coef, expon; 44 scanf_s("%d %d", &coef, &expon); 45 while (coef!=0 && expon != 0) 46 { 47 struct PolyNode* node = (struct PolyNode*)malloc(sizeof(struct PolyNode)); 48 node -> coefficient = coef; 49 node -> exponent = expon; 50 node->next = NULL; 51 (*p) ->next = node; 52 (*p) = node; 53 scanf_s("%d %d", &coef, &expon); 54 } 55 (*p) = head; 56 (*p) = (*p) -> next; 57 } 58 59 //将比较之后的项插入到新链的尾部 60 void Attach(int c, int e, Polynomial *pRear) 61 { 62 Polynomial P = (Polynomial)malloc(sizeof(struct PolyNode)); 63 P -> coefficient = c; 64 P ->exponent = e; 65 (*pRear)->next = P; 66 P->next = NULL; 67 (*pRear) = P; //因为这里改变了形参pRear的指向,所以参数列表必须传二级指针 68 } 69 70 int Compare(int exponent1, int exponent2) 71 { 72 if (exponent1 == exponent2) 73 return 0; 74 else 75 if (exponent1 > exponent2) 76 return 1; 77 return -1; 78 } 79 80 //比较两个多项式的各项,依次插入到新项 81 Polynomial PolyAdd(Polynomial P1, Polynomial P2) 82 { 83 Polynomial front, rear, temp; 84 int sum; 85 rear = front = (Polynomial)malloc(sizeof(struct PolyNode)); 86 while (P1 && P2) 87 { 88 switch (Compare(P1->exponent, P2->exponent)) 89 { 90 case 1: 91 Attach(P1->coefficient, P1->exponent, &rear); 92 P1 = P1->next; 93 break; 94 95 case -1: 96 Attach(P2->coefficient, P2->exponent, &rear); 97 P2 = P2->next; 98 break; 99 100 case 0: 101 sum = P1->coefficient + P2->coefficient; 102 if (sum) 103 Attach(sum, P1->exponent, &rear); 104 P1 = P1->next; 105 P2 = P2->next; 106 break; 107 } 108 } 109 for (; P1; P1 = P1->next) 110 Attach(P1->coefficient, P1->exponent, &rear); 111 for (; P2; P2 = P2->next) 112 Attach(P2->coefficient, P2->exponent, &rear); 113 114 temp = front; 115 front = front->next; 116 free(temp); 117 return front; 118 } 119 120 void printPolynomial(Polynomial P) 121 { 122 Polynomial node = P; 123 if (P) 124 { 125 for (; node ; node = node->next) 126 printf("%dX^%d ", node->coefficient, node->exponent); 127 printf("\n"); 128 } 129 return; 130 }
以上是关于两个一元多项式相加的主要内容,如果未能解决你的问题,请参考以下文章