问题描述
编写一元多项式加法运算程序。要求用线性链表存储一元多项式(参照课本)。该程序有以下几个功能:
- 多项式求和
输入:输入三个多项式,建立三个多项式链表Pa、Pb、Pc
(提示:调用CreatePolyn(polynomial &P,int m)。
输出:显示三个输入多项式Pa、Pb、Pc、和多项式Pa+Pb、多项式Pa+Pb+Pc
(提示:调用AddPolyn(polynomial &Pa, polynomial Pb), 调用PrintPolyn(polynomial P))。
输入
根据所选功能的不同,输入格式要求如下所示(第一个数据是功能选择编号,参见测试用例):
- 1
多项式A包含的项数,以指数递增的顺序输入多项式A各项的系数(整数)、指数(整数)
多项式B包含的项数,以指数递增的顺序输入多项式B各项的系数(整数)、指数(整数)
多项式C包含的项数,以指数递增的顺序输入多项式C各项的系数(整数)、指数(整数) - 0 ---操作终止,退出。
输出
对应一组输入,输出一次操作的结果(参见测试用例)。
- 1 多项式输出格式:以指数递增的顺序输出: <系数,指数>,<系数,指数>,<系数,指数>,参见测试用例。零多项式的输出格式为<0,0>
- 0 无输出
样例
输入(1)
1
2
1 1 2 2
2
1 1 2 2
2
1 1 2 2
输出(1)
<1,1>,<2,2>
<1,1>,<2,2>
<1,1>,<2,2>
<2,1>,<4,2>
<3,1>,<6,2>
输入(2)
1
2
6 3 8 6
2
3 4 4 8
3
1 1 5 5 9 9
输出(2)
1
2
6 3 8 6
2
3 4 4 8
3
1 1 5 5 9 9
输入(3)
1
2
1 1 2 2
2
-1 1 -2 2
2
1 1 2 2
输出(3)
<1,1>,<2,2>
<-1,1>,<-2,2>
<1,1>,<2,2>
<0,0>
<1,1>,<2,2>
代码
#include<stdio.h>
#include<stdlib.h>
struct node
{
int x;
int exp;
struct node* next;
};
struct node* read()
{
struct node *p,*q,*r;
int c,e,n;
scanf("%d",&n);
p=(struct node*)malloc(sizeof(struct node));
q=p;
for(int i=1;i<=n;i++)
{
scanf("%d %d",&c,&e);
struct node *tmp;
tmp=(struct node*)malloc(sizeof(struct node));
tmp->x=c;
tmp->exp=e;
tmp->next=NULL;
q->next=tmp;
q=q->next;
}
p=p->next;
return p;
}
struct node *add(struct node* p1,struct node* p2)
{
struct node *front,*rear,*temp;
int sum;
rear=(struct node*)malloc(sizeof(struct node));
front=rear;
while(p1&&p2)
{
if((p1->exp)==(p2->exp))
{
int sum;
sum=p1->x+p2->x;
if(sum!=0)
{
struct node* tmp1;
tmp1=(struct node*)malloc(sizeof(struct node));
tmp1->x=sum;
tmp1->exp=p1->exp;
rear->next=tmp1;
rear=rear->next;
rear->next=NULL;
}
p1=p1->next;
p2=p2->next;
}
else if(p1->exp<p2->exp)
{
struct node* tmp2;
tmp2=(struct node*)malloc(sizeof(struct node));
tmp2->x=p1->x;
tmp2->exp=p1->exp;
rear->next=tmp2;
rear=rear->next;
rear->next=NULL;
p1=p1->next;
}
else if(p1->exp>p2->exp)
{
struct node* tmp3;
tmp3=(struct node*)malloc(sizeof(struct node));
tmp3->x=p2->x;
tmp3->exp=p2->exp;
rear->next=tmp3;
rear=rear->next;
rear->next=NULL;
p2=p2->next;
}
}
while(p1)
{
struct node *tmp4;
tmp4=(struct node*)malloc(sizeof(struct node));
tmp4->x=p1->x;
tmp4->exp=p1->exp;
rear->next=tmp4;
rear=rear->next;
rear->next=NULL;
p1=p1->next;
}
while(p2)
{
struct node *tmp5;
tmp5=(struct node*)malloc(sizeof(struct node));
tmp5->x=p2->x;
tmp5->exp=p2->exp;
rear->next=tmp5;
rear=rear->next;
rear->next=NULL;
p2=p2->next;
}
rear->next=NULL;
temp=front;
front=front->next;
free(temp);
return front;
}
void print(struct node *p)
{
int flag;
struct node *head;
head=p;
while(head)
{
if(head->next!=NULL)
{
printf("<%d,%d>,",head->x,head->exp);
flag=1;
}
else
{
printf("<%d,%d>\n",head->x,head->exp);
flag=1;
}
head=head->next;
}
if(flag==0||p==NULL)
{
printf("<0,0>\n");
}
}
int main()
{
int a;
scanf("%d",&a);
if(a==0)
{
return 0;
}
struct node *p1,*p2,*p3;
p1=read();
p2=read();
p3=read();
print(p1);
print(p2);
print(p3);
p1=add(p1,p2);
print(p1);
p1=add(p1,p3);
print(p1);
return 0;
}