【資料結構】單鏈表的運用 多項式加法
#include<stdio.h> #include<stdlib.h> struct mono{ int e; int c; }; struct node{ mono data; node * next; }; struct polynomial{ node firstNode; }; void createPoly(int *d,int count,polynomial * p) { int * data=d; node * pLastNode=&(p->firstNode); for(int i=0;i<count;i++) { pLastNode->next=(node *)malloc(sizeof(node)); pLastNode=pLastNode->next; pLastNode->data.e=d[2*i]; pLastNode->data.c=d[2*i+1]; pLastNode->next=NULL; }
} void printPolynomial(polynomial *p) { node *theNode=p->firstNode.next; while(theNode->next!=NULL) { printf("+%dX^%d",theNode->data.c,theNode->data.e); theNode=theNode->next; } printf("\n"); } void copyto(node *source,node *target) { node * tempOutNode=target; node * tempInNode=source; while(tempInNode!=NULL) { tempOutNode->next=(node *)malloc(sizeof(node)); tempOutNode=tempOutNode->next; tempOutNode->data.c=tempInNode->data.c; tempOutNode->data.e=tempInNode->data.e; tempInNode=tempInNode->next; } } polynomial * addPolynomial(polynomial *p1,polynomial *p2) { polynomial *result=(polynomial*)malloc(sizeof(polynomial)); result->firstNode.next=NULL; node *theNode1=p1->firstNode.next; node *theNode2=p2->firstNode.next; node *resultindex=&result->firstNode; while(theNode1!=NULL||theNode2!=NULL) { if(theNode1==NULL) { copyto(theNode2,&(result->firstNode)); break; } else if(theNode2==NULL) { copyto(theNode1,&(result->firstNode)); break; } else { if(theNode1->data.e>theNode2->data.e) { resultindex->next=(node *)malloc(sizeof(node)); resultindex=resultindex->next; resultindex->data.c=theNode1->data.c; resultindex->data.e=theNode1->data.e; resultindex->next=NULL; theNode1=theNode1->next; } else if(theNode1->data.e<theNode2->data.e) { resultindex->next=(node *)malloc(sizeof(node)); resultindex=resultindex->next; resultindex->data.c=theNode2->data.c; resultindex->data.e=theNode2->data.e; resultindex->next=NULL; theNode2=theNode2->next; } else if(theNode1->data.e==theNode2->data.e) { resultindex->next=(node *)malloc(sizeof(node)); resultindex=resultindex->next; resultindex->data.c=theNode1->data.c+theNode2->data.c; resultindex->data.e=theNode1->data.e; resultindex->next=NULL; theNode1=theNode1->next; theNode2=theNode2->next; } } } return result; } int main() { int input1[10][2]={{9,5},{8,4},{7,3},{6,6},{5,6},{4,0},{3,1},{2,1},{1,1},{0,0}}; int input2[10][2]={{9,5},{8,4},{7,3},{6,6},{5,6},{4,0},{3,1},{2,1},{1,1},{0,0}}; polynomial p1,p2; createPoly((int *)input1,10,&p1); createPoly((int *)input2,10,&p2); printPolynomial(&p1); printPolynomial(&p2); polynomial *sum=addPolynomial(&p1,&p2); printPolynomial(sum); return 0; }