[此贴子已经被作者于2006-3-25 10:14:47编辑过]
[QUOTE]#include <stdio.h>
#include <stdlib.h>
void input(struct poly **);
void poly_add(void);
void show_ans(void);
struct poly {
int coef;
int exp;
struct poly *next;
};
struct poly *sum, *eq_h1, *eq_h2, *ans_h;
void main(void)
{
printf("\n\n");
printf("%c %c %c %c %c %c %c %c %c %c %c %c \n\n",6,5,4,3,6,5,4,3,6,5,4,3);
printf(" Multinomial For Example: AxB+CxD \n\n");
printf("%c %c %c %c %c %c %c %c %c %c %c %c \n\n\n",3,4,5,6,3,4,5,6,3,4,5,6);
printf("Input the first multinomial: ");
input(&eq_h1);
printf("Input the second multinomial: ");
input(&eq_h2);
poly_add();
show_ans();
getch();
}
void input(struct poly **eq_h)
{
struct poly *prev = NULL;
char symbol = '+';
do
{
sum = (struct poly *) malloc(sizeof(struct poly));
sum->next = NULL;
scanf("%dx%d", &sum->coef, &sum->exp);
if(*eq_h == NULL)
*eq_h = sum;
else
{
if(symbol == '-') sum->coef = -(sum->coef);
prev->next = sum;
}
prev = sum;
scanf("%c", &symbol);
} while(symbol != '\n');
}
void poly_add(void)
{
struct poly *this_n1, *this_n2, *prev;
this_n1 = eq_h1;
this_n2 = eq_h2;
prev = NULL;
while(this_n1 != NULL || this_n2 != NULL)
{
sum = (struct poly *) malloc(sizeof(struct poly));
sum->next = NULL;
if(this_n1 != NULL && (this_n2 == NULL || this_n1->exp > this_n2->exp))
{
sum->coef = this_n1->coef;
sum->exp = this_n1->exp;
this_n1 = this_n1->next;
}
else
if(this_n1 == NULL || this_n1->exp < this_n2->exp)
{
sum->coef = this_n2->coef;
sum->exp = this_n2->exp;
this_n2 = this_n2->next;
}
else
{
sum->coef = this_n1->coef + this_n2->coef;
sum->exp = this_n1->exp;
if(this_n1 != NULL) this_n1 = this_n1->next;
if(this_n2 != NULL) this_n2 = this_n2->next;
}
if(sum->coef != 0)
{
if(ans_h == NULL) ans_h = sum;
else prev->next = sum;
prev = sum;
}
else free(sum);
}
}
void show_ans(void)
{
struct poly *this_n;
this_n = ans_h;
printf("The Result: ");
while(this_n != NULL)
{
printf("%dx%d", this_n->coef, this_n->exp);
if(this_n->next != NULL && this_n->next->coef >= 0)
printf("+");
this_n = this_n->next;
}
printf("\n");
}[/QUOTE]