代码部分
#include<stdio.h>
typedef struct Node *PNode;
struct Node
{
int a;
int x;
PNode next;
};
typedef struct Node *List;
List Read();//读入系数与指数的函数
List Sum(List L1,List L2);//相加
List Multiple(List L1,List L2);//相乘
void Attach(int a,int x,List *prear);//用系数和指数生成一个新的链表节点,并添加到prear的next
void Print(List L);//输出
int main()
{
List L1,L2,L;
L1=Read();
L2=Read();
L=Multiple(L1,L2);
Print(L);
printf("\n");
L=Sum(L1,L2);
Print(L);
printf("\n");
return 0;
}
List Read()
{
int n;
List rear,head,p;
head=(List)malloc(sizeof(struct Node));
head->next=NULL;
rear=head;
scanf("%d",&n);
while(n--)
{
p=(List)malloc(sizeof(struct Node));
p->next=NULL;
scanf("%d %d",&p->a,&p->x);
rear->next=p;
rear=p;
}
rear=head->next;
free(head);
return rear;
}
List Sum(List L1,List L2)
{
List rear,head,p;
head=(List)malloc(sizeof(struct Node));
head->next=NULL;
rear=head;
if(!L1&&!L2)
return NULL;
while(L1&&L2)
{
if(L1->x>L2->x)
{
Attach(L1->a,L1->x,&rear);
L1=L1->next;
}
else if(L1->x<L2->x)
{
Attach(L2->a,L2->x,&rear);
L2=L2->next;
}
else
{
if((L1->a+L2->a)!=0)
{
Attach(L1->a+L2->a,L1->x,&rear);
}
L1=L1->next;
L2=L2->next;
}
}
while(L1)
{
Attach(L1->a,L1->x,&rear);
L1=L1->next;
}
while(L2)
{
Attach(L2->a,L2->x,&rear);
L2=L2->next;
}
rear=head->next;
free(head);
return rear;
}
void Attach(int a,int x,List *prear)
{
List p;
p=(List)malloc(sizeof(struct Node));
p->a=a;
p->x=x;
p->next=NULL;
(*prear)->next=p;
(*prear)=p;
}
void Print(List L)
{
int flag=0;
if(!L)
{
printf("0 0");
return;
}
while(L)
{
if(flag)
printf(" ");
if(!flag)
flag=1;
printf("%d %d",L->a,L->x);
L=L->next;
}
return;
}
List Multiple(List L1,List L2)
{
List p1,p2,p,head1,head2,rear;
p1=L1;
p2=L2;
head1=(List)malloc(sizeof(struct Node));
rear=head1;
if(!L1||!L2)
return NULL;
while(p2)
{
p=(List)malloc(sizeof(struct Node));
p->a=p1->a*p2->a;
p->x=p1->x+p2->x;
p->next=NULL;
p2=p2->next;
rear->next=p;
rear=p;
}
rear=head1;
head1=head1->next;
free(rear);
p1=L1->next;
while(p1)
{
head2=(List)malloc(sizeof(struct Node));
rear=head2;
p2=L2;
while(p2)
{
p=(List)malloc(sizeof(struct Node));
p->a=p1->a*p2->a;
p->x=p1->x+p2->x;
p->next=NULL;
p2=p2->next;
rear->next=p;
rear=p;
}
p1=p1->next;
rear=head2;
head2=head2->next;
free(rear);
head1=Sum(head1,head2);
}
return head1;
}