线性表实现多项式相加相减
#include <stdlib.h>
#include <stdio.h>
#include<math.h>
#include<iostream>
using namespace std;
typedef struct polynode
{
int exp;//指数
int xishu;//系数
polynode* next;//指针,指向下一个节点
}polynode,*polylist;
/*
polylist headmethodCreate(polylist &L)//头插法
{
polynode *s;
int e;
int xi;
L = (polylist)malloc(sizeof(polynode));
L->next = NULL;
cin >> xi;
cin >> e;
while (e != 999)
{
s = (polynode*)malloc(sizeof(polynode));
s->exp = e;
s->xishu = xi;
s->next = L->next;
L->next = s;
cin >> xi;
cin >> e;
}
return L;
}
*/
polylist tailmethodCreate(polylist &L)//尾插法自行输入数据建立新表
{
polynode *s;//辅助指针
polynode *tail;//尾节点辅助指针
int e;
int xi;//定义系数和指数
L = (polylist)malloc(sizeof(polynode));//动态创建一个节点指针
L->next = NULL;
tail = L;
cin >> xi;//输入系数和指数
cin >> e;
while (e != 999)
{
s = (polynode*)malloc(sizeof(polynode));
s->next = NULL;
s->exp = e;
s->xishu = xi;
tail->next = s;
tail = s;
//s->next = L->next;
//L->next = s;
cin >> xi;
cin >> e;
}
//delete(tail);
return L;
}
polylist insertnew(polylist &L,polynode* &tail,int xishu1,int exp1)//尾插法给定数值数据建立新表
{
polynode* s;
s = (polynode*)malloc(sizeof(polynode));
s->next = NULL;
s->xishu = xishu1;
s->exp = exp1;
tail->next = s;
tail = s;
return L;
}
void outputall(polylist L)//全部输出
{
while ( L->next!=NULL)
{
cout << L->next->xishu <<"x^"<< L->next->exp<<"+";
L = L->next;
}
cout << "end" << endl;
//cout << "end" << endl;
}
/*polynode* gethead(polylist L)
{
return L;
}
*/
polylist jiafa(polylist L1, polylist L2, polylist &L3)
{//多项式加法:pa=pa+pb,利用两个多项式的结点构成一个新的多项式
polynode* pa;
polynode* pb;
//polynode* pc;
//int xishuc;
//polylist L3;
L3= (polynode*)malloc(sizeof(polynode));
L3->next = NULL;
polynode* tail;
//int xi, e;
//L = (polynode*)malloc(sizeof(polynode));
tail = L3;
pa = L1;
pb = L2;
//pc = L3;
//int xisuhe;
while (pa->next!= NULL && pb->next!= NULL)//pa,pb都存在
{
if (pa->next->exp == pb->next->exp)//指数相等,系数相加
{
insertnew(L3, tail,pa->next->xishu + pb->next->xishu, pa->next->exp);
pa = pa->next;
pb = pb->next;
}
else if (pa->next->exp < pb->next->exp)//指数小的插入,并且指针后移
{
insertnew(L3, tail, pa->next->xishu , pa->next->exp);
pa = pa->next;
}
else
{
insertnew(L3, tail, pb->next->xishu, pb->next->exp);
pb = pb->next;
}
}
while(pa->next != NULL)//只有pa存在,插入pa
{
insertnew(L3, tail, pa->next->xishu, pa->next->exp);
pa = pa->next;
}
while (pb->next != NULL)//只有pb存在,插入pb
{
insertnew(L3, tail, pb->next->xishu, pb->next->exp);
pb = pb->next;
}
return L3;
}
void jianfa(polylist &L1, polylist &L2)
{
}
int main()
{
//int end1;
polylist link1;
polylist link2;
polylist link3;
cout << "请输入多项式1:" << endl;
tailmethodCreate(link1);
outputall(link1);
cout << "请输入多项式2:" << endl;
tailmethodCreate(link2);
outputall(link2);
cout << "多项式和:" << endl;
outputall(jiafa(link1,link2,link3));
//cin >> end1;
//system("pause");//使输出窗口停留
}
测试数据:多项式1:2x+2x^3+2x^4+2x^8
多项式2:3x+4x^2+2x^6+3x^8+4x^12+5x^13
预期结果:5x+4x^2+2x^3+2x^4+2x^6+5x^8+4x^12+5x^13
运行结果图: