【问题描述】编写一个程序用单链表存储多项式,并实现两个一元多项式A与B相加的函数。A,B刚开始是无序的,A与B之和按降序排列。例如:
多项式A: 1.2X^0 2.5X^1 3.2X^3 -2.5X^5
多项式B: -1.2X^0 2.5X^1 3.2X^3 2.5X^5 5.4X^10
多项式A与B之和:5.4X^10 6.4X^3 5X^1
【输入形式】任意两个多项式A和B的项数及对应的系数和指数,要查询的第几项
【输出形式】多项式中某一项的系数与指数,系数保留一位小数
【输入样例】
4 1.2 0 2.5 1 3.2 3 -2.5 5
5 -1.2 0 2.5 1 3.2 3 2.5 5 5.4 10
2
【输出样例】
6.4 3
【样例说明】
第一个多项式的系数与指数对,以空格隔开
第二个多项式的系数与指数对,以空格隔开
输出第2项的系数与指数,系数与指数间用空格隔开,系数保留一位小数
【评分标准】必须用链表实现
#include<iostream>
#include<stdlib.h>
#include<iomanip>
using namespace std;
struct Node
{
double coef;
int exp;
Node *next;
};
void Create(Node *&head,int n)
{
Node *s,*tail;
head=(Node*)malloc(sizeof(Node));
tail=head;
double c; int e;
for(int i=0;i<n;i++)
{
cin>>c>>e;
s=(Node*)malloc(sizeof(Node));
s->coef=c;
s->exp=e;
tail->next=s;
tail=s;
}
tail->next=NULL;
}
void Print(Node *head,int x)
{
int i;
Node *p=head;
for(i=0;i<x;i++)
{
p=p->next;
}
cout<<fixed<<setprecision(1)<<p->coef<<' ';
cout<<p->exp;
}
void Add(Node *&head1,Node *&head2)
{
Node *p,*q,*tail;
double sum;
p=head1->next;
q=head2->next;
tail=head1;
while(p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{
tail=p;
p=p->next;
}
else if(p->exp==q->exp)
{
sum=p->coef+q->coef;
if(sum!=0)
{
p->coef=sum;
tail=p;
p=p->next;
q=q->next;
}
else
{
p=p->next;
tail->next=p;
q=q->next;
}
}
else
{
tail->next=q;
tail=q;
q=q->next;
}
}
if(p==NULL)
tail->next=q;
else
tail->next=p;
}
void Sort(Node *&head)
{
Node *p,*q;
double t1;
int t2;
for(p=head->next;p!=NULL;p=p->next)
{
for(q=p->next;q!=NULL;q=q->next)
{
if(p->exp<q->exp)
{
t1=p->coef;
t2=p->exp;
p->coef=q->coef;
p->exp=q->exp;
q->coef=t1;
q->exp=t2;
}
}
}
}
void Sort2(Node *&head)
{
Node *p,*q;
double t1;
int t2;
for(p=head->next;p!=NULL;p=p->next)
{
for(q=p->next;q!=NULL;q=q->next)
{
if(p->exp>q->exp)
{
t1=p->coef;
t2=p->exp;
p->coef=q->coef;
p->exp=q->exp;
q->coef=t1;
q->exp=t2;
}
}
}
}
int main()
{
int n,x;
Node *head1=NULL;
Node *head2=NULL;
cin>>n;
Create(head1,n);
Sort2(head1);
cin>>n;
Create(head2,n);
Sort2(head2);
Add(head1,head2);
Sort(head1);
cin>>x;
Print(head1,x);
}