实验三 一元多项式的表示及相加

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验三一元多项式的表示及相加

(实验二、三共用三周完成。)

【实验目的】

(1)掌握C语言中结构类型和指针类型,指针是逻辑关系的映像。

(2)掌握线性链表的操作特点和动态产生、输出单链表的方法。

(3)掌握单链表的插入、删除操作的特点和方法。

【实验内容】

试用单链表表示两个多项式:A=4+6x3+5x8+4x12,B=5+2x4+6x7+3x12。

(1)设计此两个多项式的数据结构;

(2)写出两个多项式相加的算法,要求除两个多项式所占空间外,不开辟新的存储空间。

【实验要求】

输出和多项式的各项系数、指数;从键盘输入x,能够计算出和多项式A+B的值并输出。

【实验提示】

(1)可用两个带头结点的单链表分别表示多项式A和B,链表结点的结构可包含:coef (系数)、exp(指数)、next(指向下一结点的指针)。结点可按指数升序排

列。

(2)可分两步完成:

①先求出“和多项式”A+B的表达式(如C=9+6x3+2x4+6x7+5x8+

7x12),存放到带头结点的链表C中;

②再将x代入,从而求得和多项式的值。

(3)求和多项式C的方法:

C中的结点无需另生成,可看成是将多项式B加到多项式A上,由此可得下列运算规则:设p和q分别指向A和B中某一结点,比较结点中的指数项,

①若p->exp < q->exp,则p结点应是“和多项式”中的一项,令p指针向后

移;

②若p->exp > q->exp,则q结点应是“和多项式”中的一项,将q结点插入在

p结点之前,且q指针在原来的链表上后移;

③若p->exp=q->exp,则将两个结点中的系数相加,当和不为零时修改p结点

中的系数,释放q结点,p, q后移;反之,“和多项式”中没有此项,从A

表中删去p结点,同时释放p和q结点,p, q后移。

程序如下:

#include "stdio.h"

#include

#include

#include

struct node

{

int coe;

int exp;

struct node *next;

};

void main()

{

int num1,num2;

double a;

struct node *ha,*hb,*hc;

struct node *input_coef(int num);

struct node *input_exp(int num,struct node *head);

void print(struct node *pp);

struct node *union_(struct node *p,struct node *q);

void count(double x,struct node *hc);

printf("请输入多项式A的项数");

scanf("%d",&num1);

printf("请输入多项式A的系数");

ha=input_coef(num1);

printf("请输入多项式A的指数");

ha=input_exp(num1,ha);

printf("请输入多项式B的项数");

scanf("%d",&num2);

printf("请输入多项式B的系数");

hb=input_coef(num2);

printf("请输入多项式B的指数");

hb=input_exp(num2,hb);

printf("多项式A的系数和指数为");

print(ha);

printf("多项式B的系数和指数为");

print(hb);

hc=union_(ha,hb);

print(hc);

printf("请输入x值:");

scanf("%lf",&a);

count(a,hc);

}

struct node *input_coef(int num)

{

int i=0;

struct node *head, *p1, *p2;

head=p2=(struct node*)malloc(sizeof(struct node*));

for(i=0;i

{

p1=(struct node*)malloc(sizeof(struct node*));

p2->next=p1;

p2=p1;

scanf("%d",&p2->coe);

}

p2->next=NULL;

return head;

}

struct node *input_exp(int num,struct node *head)

{

int i=0;

struct node *p=head->next;

for(i=0;i

{

scanf("%d",&p->exp);

p=p->next;

}

return head;

}

struct node *union_(struct node *p,struct node *q) {

struct node *headc,*c,*p0;

int i;

headc=c=p;

while(p->next!=NULL&&q->next!=NULL)

{

if(p->next->exp==q->next->exp)

{

i=p->next->coe+q->next->coe;

if(i==0)

{

p0=p->next;

p->next=p0->next;

free(p0);

p0=q->next;

q->next=p0->next;

free(p0);

}

else

{

p->next->coe=i;

p=p->next;

q=q->next;

}

}

else if(p->next->expnext->exp)

p=p->next;

else

{

p0=p->next;

p->next=q->next;

q->next=q->next->next;

p->next->next=p0;

p=p->next;

}

}

if(p->next==NULL)

p->next=q->next;

return headc;

}

void print(struct node *pp)

{

struct node*p=pp->next;

while(p)

{

printf ("%d %d ",p->coe,p->exp);

p=p->next;

}

printf("\n");

}

void count(double x,struct node *hc)

{

double y;

y=0;

相关文档
最新文档