#include <iostream>
#include <stdlib.h>
using namespace std;
struct node
{
int coefficient;
int exponent;
struct node *next;
};
struct node *creat()//建立单链表返回链表头指针,此头指针无数据
{
struct node *head,*p1,*p2;
int c,e;
head=(struct node*)malloc(sizeof(struct node));//先为头指针开一个内存
head->next=NULL;
p2=head;//为了使头指针不变,所以定义指针p2代替头指针
cin>>c>>e;
while(e!=-1)
{
p1=(struct node*)malloc(sizeof(struct node));
p1->coefficient=c;
p1->exponent=e;
p1->next=NULL;
p2->next=p1;
p2=p1;
cin>>c>>e;
}
return head;//最终该头指针无内容
}
void print(struct node *head)//输出链表
{
struct node *p;
p=head;
p=p->next;//因为头指针head为空,head->next为第一个元素,所以p=p->next;
while(p!=NULL)
{
cout<<p->coefficient<<'x'<<p->exponent<<' ';
p=p->next;
}
cout<<endl;
}
//默认输入为重小到大
struct node *add(struct node *t1,struct node*t2)//相加
{
struct node *p,*q,*prea,*preb;//建立prea和preb指针的作用在于当p和q指针要指向下一个数字的时候,先复制它们的位置
int sum; //等到判断的时候方便进行指针指向的改变
p=t1->next;//t1空,p指向第一个元素
q=t2->next;//同理
prea=t1;//把prea作为头指针
//注意while里面必须用else if而不是if因为是3个选一个进行而不是并列的进行满足一个条件会影响下一个if的判断
while(p!=NULL&&q!=NULL)
{
if(p->exponent<q->exponent)
{
prea=p;
p=p->next;
}
else if(p->exponent==q->exponent)
{
sum=p->coefficient+q->coefficient;
if(sum!=0)
{
p->coefficient=sum;
prea=p;
preb=q;
p=p->next;
q=q->next;
}
if(sum==0)//正负相加为0
{
p=p->next;
preb=q;
prea->next=p;
q=q->next;
}
}
else
if(p->exponent>q->exponent)//插入
{
preb=q;
q=q->next;
preb->next=p;
prea->next=preb;
prea=prea->next;
}//这个里面没有浦p=p->next是因为当插入完之后preb与p进行判断看是否可以进行合并同类项
}
if(q!=NULL)
prea->next=q;
return t1;
}
int main()
{
struct node *heada,*headb,*headc;
heada=creat();
print(heada);
headb=creat();
print(headb);
headc=add(heada,headb);
print(headc);
}
使用链表求一元多项式的和
最新推荐文章于 2022-05-21 16:23:30 发布