c语言实现一元多项式
[cpp]/*
* Ploly.c
*
* Created on: 2012-12-3
* Author: Administrator
*/
#include <stdio.h>
#include <stdlib.h>
#define DEV 0.0000002
#define TRUE 1
#define OK 1
#define ERROR 0 www.zzzyk.com
#define CHECK(t) do{if(!(t)){return 0;}}while(0)
typedef int Status;
typedef struct term {
double coef;
int expn;
struct term *next;
} PolyNode, *Poly;
Status makeNode(double coef, int expn, Poly *p) {
(*p) = (Poly) malloc(sizeof(struct term));
CHECK(*p);
(*p)->coef = coef;
(*p)->expn = expn;
(*p)->next = 0;
return OK;
}
Status destoryPoly(Poly *head) {
Poly p = *head;
while (p) {
*head = p->next;
free(p);
p = *head;
}
*head = 0;
return OK;
}
Status AddNodePoly(Poly *head, double coef, int expn) {
CHECK(*head);
if (abs(coef) < DEV)
return OK;
Poly q = (*head)->next;
Poly p = (*head);
Poly s;
while (q && expn < q->expn) {
p = q;
q = q->next;
}
if (q == 0 || expn > q->expn) {
CHECK(makeNode(coef, expn,&s));
p->next = s;
s->next = q;
} else {
q->coef += coef;
if (q->coef == 0) {
p->next = q->next;
free(q);
}
}
return OK;
}
Status createPoly(Poly *head) {
if (*head)
destoryPoly(head);
CHECK(makeNode(0,0,head));
int expn;
double coef;
do {
scanf("%lf%d", &coef, &expn);
if (abs(coef) < DEV && expn == 0)
break;
if (abs(coef) < DEV
)
continue;
if (!AddNodePoly(head, coef, expn)) {
return ERROR;
}
} while (TRUE);
return OK;
}
Status print(Poly head) {
CHECK(head);
Poly p = head->next;
while (p) {
printf("%1.1f", p->coef);
if (p->expn)
printf("*x^%d", p->expn);
if (p->next && p->next->coef > 0)
printf("+");
p = p->next;
}
printf("\n");
return OK;
}
Status AddPoly(Poly *a, Poly *b) {
CHECK(*a&&*b&&*a!=*b);
Poly p = *a,p1 = (*a)->next,p2 = (*b)->next,t;
while (p1 && p2) {
if (p1->expn == p2->expn) {
p1->coef = p1->coef + p2->coef;
if (p1->coef == 0) {
t = p1->next;
free(p1);
p1 = t;
} else {
p->next = p1;
p1 = p1->next;
p = p->next;
}
t = p2->next;
free(p2);
p2 = t;
} else {
t = p1->expn > p2->expn ? p1 : p2;
p->next = t;
p = t;
t = t->next;
p1->expn > p2->expn ? p1 : p2 = t;
}
}
p->next = 0;
if(p2){
p->next = p2;
}
free(b);
b = 0;
return OK;
}
Status SubPoly(Poly *a, Poly *b) {
CHECK(*a&&*b&&*a!=*b);
Poly p = (*b)->next;
补充:软件开发 , C语言 ,