前言
- 时间:2020.3.22
- 内容:小实验题 一元多项式加减乘
- 备注:我写的比较麻烦,因为比较赶就没细想更好的办法。。好像不太难,可是中途出现无数小问题,最后还是debug解决,debug万岁哈哈哈!代码可以直接复制粘贴在codeblock里用,另外需要在调试时查看链表内的元素,可以打开watch界面,自带的是链表L的地址,基本没啥用处,需要的话可以自己添加,采用L->next.data.coef以及L->next->next.data.coef这样的形式,即可查看链表内的元素值。
- 关于优化:可以增加一个专门化简多项式的函数,比如次数相同的可以加起来,系数为0的舍去等等。还可以增加一个头插法和尾插法函数,让中间的重复冗余代码少一些 。结点s必须要在while里面一遍遍创建,好像还有别的途径等等。。反正很多可以优化的地方啦。。这个只是勉强能实现功能。
简单实现输入输出
可以用于测试。
- 输入term组项数
- 再输入各组项的系数和指数
- 输出一个由上述项数组成的多项式
#include <stdio.h>
#include <malloc.h>
using namespace std;
typedef struct{
double coef;
int expn;
}ElemType;
typedef struct Lnode{
ElemType data;
struct Lnode *next;
}*LinkList;
void InitList(LinkList &L){
L =(LinkList)malloc(sizeof(Lnode));
L->next = NULL;
}
void CreatPoly(LinkList &L,int term){
ElemType e;
LinkList p,q,s;
InitList(L);
p = L;
q = L->next;
printf("Input elem of %d polynomial: \n",term);
while(term--){
InitList(s);
scanf("%lf",&e.coef);
scanf("%d",&e.expn);
s->data.coef = e.coef;
s->data.expn = e.expn;
//first elem
if(q==NULL){
p->next = s;
q = s;
}
else{
//input elem-exp is not min than right --> move p q a right step
while(q && q->data.expn < e.expn){
p = p->next;
q = p->next;
}
//input elem-exp is min than right --> p s q
if(q){
s->next = q;
p->next = s;
q = s;
}
//max elem-exp -> the most right elem-exp
else{
p->next = s;
q = s;
}
}
}
}
void ShowPoly(LinkList L){
LinkList p;
p = L->next;
if(p){
printf("%.2lfX^(%d)",p->data.coef,p->data.expn);
p = p->next;
}
while(p!=NULL){
if(p->data.coef >= 0)
printf("+");
printf("%.2lfX^(%d)",p->data.coef,p->data.expn);
p = p->next;
}
printf("\n\n");
}
int main()
{
LinkList L1,L2;
int term1,term2;
printf("Input term of the polynomial P(X): ");
scanf("%d",&term1);
CreatPoly(L1,term1);
ShowPoly(L1);
printf("Input term of the polynomial Q(X): ");
scanf("%d",&term2);
CreatPoly(L2,term2);
ShowPoly(L2);
return 0;
}
加减乘完整版
- 还在写。。写完就发上来