数据结构实验报告-一元多项式 下载本文

内容发布更新时间 : 2024/11/16 16:36:51星期一 下面是文章的全部内容请认真阅读。

h = La = (LNode*)malloc(sizeof(LNode)); La->next = NULL; while (qa && qb) {

switch (Compare(qa,qb)) { case -1:

La->next = qb; La = qb;

qb = qb->next; break; case 0:

sum = qa->coef + qb->coef; if (sum != 0.0) { La->next = qa; qa->coef = sum; La = qa;

qa = qa->next; }

else { Lb = qa;

qa = qa->next; free(Lb); }

Lb = qb;

qb = qb->next; free(Lb); break; case 1:

La->next = qa; La = qa;

qa = qa->next; break; } }

if (Pa) La->next = qa; if (Pb) La->next = qb; Lb = h;

h = h->next; free(Lb); return h; }

LNode* Add(LNode *Pa, LNode *Pb) { int n;

puts(\再输入1个一元多项式的项数\scanf(\

11

Pb = InitPolyn(Pb,n); Pb = selsort(Pb); PrintfPoly(Pa);

if(Pb && Pb->coef>0) printf(\PrintfPoly(Pb);

Pa = AddPolyn(Pa,Pb); printf(\Pa = selsort(Pa); PrintfPoly(Pa); return Pa; }

LNode* SubtractPolyn(LNode *Pa, LNode *Pb) { LNode *La = Pb; while(La) { La->coef *= -1; La = La->next; }

return AddPolyn(Pa,Pb); }

LNode* Subtract(LNode *Pa, LNode *Pb) { int n;

puts(\再输入1个一元多项式的项数\scanf(\

Pb = InitPolyn(Pb,n); Pb = selsort(Pb); PrintfPoly(Pa); printf(\

putchar('(');PrintfPoly(Pb);putchar(')'); Pa = SubtractPolyn(Pa,Pb); printf(\Pa = selsort(Pa); PrintfPoly(Pa); return Pa; }

LNode* MultiplyPolyn(LNode *Pa, LNode *Pb) { if(!Pb) return NULL;

LNode *pa = Pa, *p, *q, *r, *s, *t; r = p = (LNode*)malloc(sizeof(LNode)); while(pa) {

p->coef = pa->coef; p->expn = pa->expn; q = p;

p = p->next = (LNode*)malloc(sizeof(LNode)); pa = pa->next;

12

}

q->next = NULL; free(p); pa = Pa;

t = s = (LNode*)malloc(sizeof(LNode)); while(pa) { q = s;

s = s->next = (LNode*)malloc(sizeof(LNode)); pa = pa->next; }

q->next = NULL; free(s); pa = Pa; while(pa) {

pa->coef *= Pb->coef; pa->expn += Pb->expn; pa = pa->next; }

Pb = Pb->next; while(Pb) { p = r; s = t; while(p) {

s->coef = p->coef * Pb->coef; s->expn = p->expn + Pb->expn; p = p->next; s = s->next; }

Pa = AddPolyn(Pa,t); Pb = Pb->next; }

return Pa; }

LNode* Multiply(LNode *Pa, LNode *Pb) { int n;

puts(\再输入1个一元多项式的项数\scanf(\

Pb = InitPolyn(Pb,n); Pb = selsort(Pb);

putchar('(');PrintfPoly(Pa);putchar(')'); printf(\

putchar('(');PrintfPoly(Pb);putchar(')'); printf(\

Pa = MultiplyPolyn(Pa,Pb);

13

Pa = selsort(Pa); PrintfPoly(Pa); return Pa; }

void main() { LNode *A,*B; char s[2]; int i,n;

printf(\printf(\一元多项式计算\\n \

printf(\printf(\王伟 ###\\n\puts(\输入1个一元多项式的项数\scanf(\A = InitPolyn(A,n); A = selsort(A); PrintfPoly(A);

p: puts(\加\\n2:减\\n3:乘\\n4:退出\getchar(); q: gets(s);

if(s[1]!='\\0' || !isdigit(*s)) { puts(\,请重新输入!\}

i = *s-48; switch(i) {

case 1:A = Add(A,B);goto p;;

case 2:A = Subtract(A,B);goto p;; case 3:A = Multiply(A,B);goto p; case 4:break;

default:puts(\请重新输入!\} }

14

六、程序运行效果图与说明

例:x^2+3x^4

(1) 按照需要操作的多项式输入第1个多项式的项数 例中多项式项数为2,输入2,回车;

(2) 依次输入两个非零项,两个项之间用空格间开即可,每项输入,前一

15