PAGE
PAGE 1
实验报告——线性表应用
实验目的
用单链表储存一元多项式,并实现两个多项式的相加运算。
实验内容
先创建链表,存储多项式;
输出多项式;
两个多项式相加;
输出多项式。
程序代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//一元多项式链式储存的节点结构
typedef struct Polynode
{
float coef;
int exp;
struct Polynode * next;
} Polynode , * Polylist;
//建立一元多项式的链表
Polylist polycreate()
{
Polynode * head,* rear,* s;
float c;
int e;
head=(Polynode* )malloc(sizeof(Polynode));
rear=head;
scanf("%f,%d",&c,&e);
while(c!=0)
{
s=(Polynode * )malloc(sizeof(Polynode));
s->coef=c;
s->exp=e;
rear->next=s;
rear=s;
scanf("%f,%d",&c,&e);
}
rear->next=NULL;
return(head);
}
//输出多项式
void print(Polynode*L)
{
Polynode*p;
p=L->next;
printf("a=");
if(p&&p->coef!=0)
printf("%.2f*x^%d",p->coef,p->exp);
while(p->next!=NULL)
{
if((p->next->coef)>0&&p)
printf("+");
else
printf("-");
p=p->next;
printf("%.2f*x^%d",fabs(p->coef),p->exp);
}
}
//多项式相加?
void polyadd(Polylist polya,Polylist polyb)
{
Polynode*p,*q,*tail,*temp;
int sum;
p=polya->next;
q=polyb->next;
tail=polya;
while (p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{tail ->next=p; tail=p;p=p->next;}
else if (p->exp==q->exp);
{sum=p->coef+q->coef;
if(sum!=0)
{p->coef=sum;
tail->next=p;tail=p;
p=p->next;
temp=q;q=q->next;free(temp);
}
else
{
temp=p;p=p->next;free(temp);
temp=q;q=q->next;free(temp);
}
}
{tail ->next=q;tail=q;
q=q->next;}
}
if(p!=NULL)
tail->next=p;
else
tail->next=q;
}
void main()
{
Polynode*a,*b;
printf("输入a的系数和指数:\n");
a = polycreate();
print(a);
printf("\n");
printf("输入b的系数和指数:\n");
b = polycreate();
print(b);
printf("\n");
polyadd(a,b);
printf("两个多项式的和为:\n");
print(a);
}
实验结果
实验过程中遇到的问题及处理方法
程序运行时,在中文状态下输入“,”回车后就不能再输入了,应在英文状态下输入“,”。
- 下载文档
- 收藏
- 0