多项式相加
#include <stdio.h> #include <stdlib.h> typedef struct PolyNode *PtrToNode; //定义链表节点,也就是多项式中的某一项; typedef struct PolyNode { int Coeff; int Exponent; PtrToNode Next; } PolyNode; typedef PtrToNode Polynomial; /************************************************************ *多项式相加的函数: *P、Q为存储两个多项式各项的单链表(含头结点) *Sum为多项式相加结果存放的单链表 * ************************************************************/ void AddPolynomial(Polynomial P,Polynomial Q,Polynomial Sum) { Polynomial PIndex,QIndex,SumIndex; PIndex = P->Next; QIndex = Q->Next; SumIndex = Sum; while(!(PIndex == NULL && QIndex == NULL)) { if(PIndex==NULL) { SumIndex->Next = QIndex; QIndex = QIndex->Next; SumIndex = SumIndex->Next; } else if(QIndex == NULL) { SumIndex->Next = PIndex; PIndex = PIndex->Next; SumIndex = SumIndex->Next; } else { if(PIndex->Exponent > QIndex->Exponent) { SumIndex->Next = PIndex; PIndex = PIndex->Next; SumIndex = SumIndex->Next; //continue在判断下面if条件时会有异常,类似Java //的空引用异常 continue; } if(PIndex->Exponent == QIndex->Exponent) { Polynomial PP =(Polynomial) malloc(sizeof(struct PolyNode)); PP->Exponent = PIndex->Exponent; PP->Coeff = PIndex->Coeff + QIndex->Coeff; SumIndex->Next = PP; PIndex = PIndex->Next; QIndex = QIndex->Next; SumIndex = SumIndex->Next; continue; } if(PIndex->Exponent < QIndex->Exponent) { SumIndex->Next = QIndex; QIndex = QIndex->Next; SumIndex = SumIndex->Next; continue; } } } SumIndex->Next = NULL; } /************************************************************ *遍历单链表(含头结点)函数: *P:待遍历的链表 *************************************************************/ void TraversePolynomial(Polynomial P) { Polynomial Tmp = P->Next; while(Tmp != NULL) { printf("Coeff is %d and Exponent is %d\n",Tmp->Coeff,Tmp->Exponent); Tmp = Tmp->Next; } } int main( ) { Polynomial Poly1,Poly2,Poly3,Poly11,Poly22; int i,j; Poly1 =(Polynomial) malloc(sizeof(struct PolyNode)); Poly2 =(Polynomial) malloc(sizeof(struct PolyNode)); Poly3 =(Polynomial) malloc(sizeof(struct PolyNode)); Poly11 = Poly1; Poly22 = Poly2; //创建两个链表时,需要保证是按照指数递减的方式构造的 for(i = 5;i >= 1;i--) { Polynomial Tmp =(Polynomial) malloc(sizeof(struct PolyNode)); Tmp->Coeff = i; Tmp->Exponent = i; Poly11->Next = Tmp; Poly11 = Poly11->Next; } Poly11->Next = NULL; for(j = 11;j >= 3;j--) { Polynomial Tmp =(Polynomial) malloc(sizeof(struct PolyNode)); Tmp->Coeff = j; Tmp->Exponent = j; Poly22->Next = Tmp; Poly22 = Poly22->Next; } Poly22->Next = NULL; TraversePolynomial(Poly1); printf("*****************************************\n"); TraversePolynomial(Poly2); AddPolynomial(Poly1,Poly2,Poly3); printf("*****************************************\n"); TraversePolynomial(Poly3); return 0; }