标签:
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 typedef struct polynomial 5 { 6 int coef; 7 int expn; 8 struct polynomial *next; 9 }node; 10 11 node *creat() 12 { 13 node *p,*q,*h; 14 int expn,coef; 15 h=(node*)malloc(sizeof(node)); 16 p=h; 17 printf("enter your coef and expn\n"); 18 scanf("%d%d",&coef,&expn); 19 while(coef!=0) 20 { 21 q=(node*)malloc(sizeof(node)); 22 q->coef=coef;q->expn=expn; 23 p->next=q; 24 p=q; 25 scanf("%d%d",&coef,&expn); 26 } 27 p->next=NULL; 28 return h; 29 } 30 31 void print(node *h) 32 { 33 node *p; 34 p=h; 35 while(p->next!=NULL) 36 { 37 p=p->next; 38 if(p->next!=NULL) 39 printf("%dX^%d+",p->coef,p->expn); 40 else 41 printf("%dX^%d\n",p->coef,p->expn); 42 } 43 44 } 45 46 node *mul(node*ha,node*hb) 47 { 48 node*p1,*p2,*p,*h,*q; 49 p1=ha;p2=hb; 50 h=(node*)malloc(sizeof(node)); 51 p=h; 52 while(p1->next!=NULL) 53 { 54 p1=p1->next; 55 while(p2->next!=NULL) 56 { 57 p2=p2->next; 58 q=(node*)malloc(sizeof(node)); 59 q->coef=p1->coef*p2->coef; 60 q->expn=p1->expn+p2->expn; 61 p->next=q; 62 p=q; 63 } 64 p2=hb; 65 } 66 p->next=NULL; 67 return h; 68 } 69 70 node *simp(node*hc) 71 { 72 node *p,*q,*set; 73 set=hc; 74 p=hc->next; 75 while(set->next!=NULL) 76 { 77 set=set->next; 78 while(p->next!=NULL) 79 { 80 q=p; 81 p=p->next; 82 if(set->expn==p->expn) 83 { 84 set->coef+=p->coef; 85 q->next=p->next; 86 q=p; 87 p=p->next; 88 free(q); 89 } 90 } 91 p=set->next; 92 } 93 return hc; 94 } 95 96 int main() 97 { 98 printf("Hello world!\n"); 99 node *h1,*h2,*h3,*h4; 100 printf("the first one is coef/n"); 101 h1=creat(); 102 print(h1); 103 printf("the second one is expen/n"); 104 h2=creat(); 105 print(h2); 106 printf("the third one is mul\n"); 107 h3=mul(h1,h2); 108 h4=simp(h3); 109 print(h4); 110 return 0; 111 }
标签:
原文地址:http://www.cnblogs.com/guangluwutu/p/5385039.html