这个C++程序的问题?(单链表实现两个多项式相乘)

来源:百度知道 编辑:UC知道 时间:2024/09/21 01:25:01
#include <iostream>
using namespace std;
struct list
{
int coef;//系数
int exp;//指数
list *next;
};
list *Creat()//创建带头结点的链表
{
list *h,*r,*s;//h是头结点,存放项的个数,指向第一项
r=h=new list;
h->next=NULL;
while(1)
{
s=new list;
cin>>s->coef>>s->exp;
if(s->coef==0)
break;
if(h->next==NULL)
{
r=s;//r=h->next
h->next=r;
}
else
{
r->next=s;
r=s;
}
}
r->next=NULL;
return h;
}
void Display(list *h)//输出链表
{
list *p;
p=h->next;
cout<<"f(x)=";
while(p)
{
if(p->next!=NULL)
cout<<p->coef<<"X^"<<p->exp<<"+";
else
cout<<p->coef<<"X^"<<p->exp;
p=p->next;
}
cout<<endl;

很难找出,不好读,给你写一个很清楚的,调试已通过:

list *Multiply(list *h1,list *h2)//实现两个链表相乘
{
// h1 * h2
list *result = new list;
result->next = NULL;
list *temp = result;

list *p1, *p2;

p1 = h1->next;
while (p1)
{
p2 = h2->next;
while (p2)
{
list *q = new list;
q->coef = p1->coef * p2->coef;
q->exp = p1->exp + p2->exp;

temp->next = q;
q->next = NULL;
temp = q;

p2 = p2->next;
}
p1 = p1->next;
}

result = Huajian(result);
return result;
}

list *Multiply(list *h1,list *h2)//实现两个链表相乘
{
// h1 * h2
list *result = new list;
result->next = NULL;
list *temp = result;

list *p1, *p2;