数据结构试验作业,上课写的一个有关二项式的东东:
1: #include <stdio.h>
2: #include <malloc.h>
3:
4: typedef struct Polynode {
5: int coef;
6: int exp;
7: struct Polynode *next;
8: } *Polylist;
9:
10: Polylist createPoly() {
11: Polylist p,p0;
12: Polylist h = (Polylist)malloc(sizeof(Polylist));
13: if(h!=NULL) {
14: h->coef=0;
15: h->exp=0;
16: h->next=NULL;
17: printf("Please input num as format *,* /n To end input 0,0/n");
18: do {
19: if((p=(Polylist) malloc(sizeof(Polylist)))!=NULL) {
20: scanf("%d,%d",&p->coef,&p->exp);
21: fflush(stdin);
22: p0=h; p->next=NULL;
23: while(p0->next&&p->exp<(p0->next)->exp) p0=p0->next;//find the right place
24: if(p0->next&&p->exp==(p0->next)->exp) { //judge if they are equal
25: p0->next->coef += p->coef;//add together
26: } else {
27: p->next=p0->next; //insert
28: p0->next=p;
29: }
30: }
31: } while (p->exp!=0);
32: }
33: return h;
34: }
35:
36: void print(Polylist p) {
37: p=p->next;
38: if(p->next!=NULL) {
39: printf("%dx^%d",p->coef,p->exp);
40: p=p->next;
41: }
42: while(p->next!=NULL) {
43: printf("+%dx^%d",p->coef,p->exp);
44: p=p->next;
45: }
46: }
47:
48: Polylist addPoly(Polylist p1, Polylist p2) {
49: Polylist h,p,k1,k2;
50: h = (Polylist) malloc (sizeof(Polylist));
51: if(h==NULL) return 0;
52: h->coef=0;
53: h->exp=0;
54: h->next=NULL;
55:
56: p=h;
57: k1=p1->next;
58: k2=p2->next;
59: while(k1->next&&k2->next) {
60: if(k1->exp < k2->exp) {
61: p->next=k1;
62: p=p->next;
63: k1=k1->next;
64: } else if(k1->exp > k2->exp) {
65: p->next=k2;
66: p=p->next;
67: k2=k2->next;
68: } else if(k1->exp == k2->exp) {
69: if(0 != k1->coef + k2->coef) {
70: k1->coef += k2->coef;
71: p->next=k1;
72: p=p->next;
73: k1=k1->next;
74: }
75: } //if
76: } //while
77: if(k1->next) { //if k1 is longer
78: p->next=k1->next;
79: } else if(k2->next){
80: p->next=k2->next;
81: }
82: return h;
83: }
84:
85: void main() {
86: Polylist polylist1,polylist2,addResult;
87:
88: //Input the Polylist data
89: printf("Input the first Polylist:/n");
90: polylist1=createPoly();
91: printf("Input the second Polylist:/n");
92: polylist2=createPoly();
93:
94: //show the Polylist
95: printf("/nPolylist1:");print(polylist1);
96: printf("/nPolylist1:");print(polylist2);
97:
98: //add the two Polylist
99: addResult=addPoly(polylist1,polylist2);
100:
101: //show the result
102: printf("/nAddResult:");print(addResult);
103:
104: }
105: