C++链表多项式加减运算问题

#include<iostream>usingnamespacestd;structpolynomial{doublecoef;//系数intexp;//指数polyno... #include<iostream>
using namespace std;

struct polynomial
{
double coef; // 系数
int exp; // 指数
polynomial *next;
}*headA,*headB,*addAB,*cutAB;

void insert(polynomial * head ,double c,int e)
{
polynomial *p = head,*q;
q =new polynomial;
q -> coef = c;
q -> exp = e;
q -> next = NULL;

while(p->next)
{
if(p->next->exp < e)
break;
if(p->next->exp == e)
{
p -> next -> coef += q -> coef;
return ;
}
p = p->next;
}

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

}

void print(polynomial * head)
{
int i = 0;
polynomial * ptemp = head -> next;
for(;ptemp!= NULL;ptemp = ptemp->next)
{
if(!ptemp -> coef)
continue;
cout<<ptemp->coef;

if(ptemp -> exp == 0)
cout<<"";
else if(ptemp -> exp == 1)
cout<<"X";
else
cout<<"X"<<ptemp -> exp;

if(ptemp -> next &&ptemp -> coef > 0)
cout<<" + ";
else cout<<" ";

i++;
}

}

void add()
{
addAB -> next = NULL;
polynomial *ptemp = addAB;
polynomial *p1 = headA->next,*p2 = headB->next;
for(;p1 != NULL;p1 = p1->next)
insert(addAB,p1->coef,p1->exp);

for(;p2 != NULL;p2 = p2->next)
insert(addAB,p1->coef,p1->exp);
}
void cut()
{
cutAB -> next = NULL;
polynomial *ptemp = cutAB;
polynomial *p1 = headA->next,*p2 = headB->next;
for(;p1 != NULL;p1 = p1->next)
insert(cutAB,- (p1->coef),p1->exp);

for(;p2 != NULL;p2 = p2->next)
insert(cutAB,-(p1->coef),p1->exp);

}

void creat(polynomial * head)
{
head -> next = NULL;
double c;
int e;
while(e>=0)
{
cout<<"input a coef and a exp (exp<0 to end)"<<endl;
cin>>c>>e;
insert(head,c,e);
}

}

int main()
{
cout<<"creat A polynomial"<<endl;
creat(headA);
cout<<"headA = ";
print(headA);

cout<<"creat B polynomial"<<endl;
creat(headB);
cout<<"headB = ";
print(headB);

cout<<"A polynomial add B polynomial"<<endl;
add();
print(addAB);

cout<<"A polynomial minus B polynomial"<<endl;
cut();
print(cutAB);
}
展开
 我来答
arick1
2012-06-24
知道答主
回答量:28
采纳率:0%
帮助的人:25.2万
展开全部
果断用堆栈做吧!简单得多
更多追问追答
追问
要求用链表啊
追答
用链表模拟堆栈的工作模式呗
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式