#include <stdio.h>
#include <stdlib.h>
struct Node{
int a;
int x;
struct Node *next;
};
int main(void){
struct Node *head1 = (struct Node*)malloc(sizeof(struct Node)); // 第一个多项式头指针
struct Node *head2 = (struct Node*)malloc(sizeof(struct Node)); // 第二个多项式头指针
head1->next = NULL; head2->next = NULL;
struct Node *tmp1 = head1, *tmp2 = head2;
int len_head1, len_head2;
puts("请输入多项式1的项数: ");
scanf("%d", &len_head1);
puts("请输入多项式1:");
for(int i = 1; i <= len_head1; i++){
struct Node *p = (struct Node*)malloc(sizeof(struct Node));
scanf("%d%d",&p->a,&p->x);
tmp1->next = p;
tmp1 = p;
}
tmp1->next = NULL;
puts("请输入多项式2的项数: ");
scanf("%d", &len_head2);
puts("请输入多项式2:");
for(int i = 1; i <= len_head2; i++){
struct Node *p = (struct Node*)malloc(sizeof(struct Node));
scanf("%d%d",&p->a,&p->x);
tmp2->next = p;
tmp2 = p;
}
tmp2->next = NULL;
tmp1 = head1->next, tmp2 = head2->next;
struct Node *ans = (struct Node*)malloc(sizeof(struct Node));
ans->next = NULL;
struct Node *ans_head = ans;
while(tmp1 && tmp2){
if(tmp1->x > tmp2->x) {
struct Node *tmp = (struct Node *) malloc(sizeof(struct Node));
tmp->x = tmp1->x;
tmp->a = tmp1->a;
ans_head->next = tmp;
ans_head = tmp;
tmp1 = tmp1->next;
}
else if(tmp2->x > tmp1->x){
struct Node *tmp = (struct Node *) malloc(sizeof(struct Node));
tmp->x = tmp2->x;
tmp->a = tmp2->a;
ans_head->next = tmp;
ans_head = tmp;
tmp2 = tmp2->next;
}
else {
struct Node *tmp = (struct Node *) malloc(sizeof(struct Node));
tmp->x = tmp1->x;
tmp->a = tmp2->a + tmp1->a;
ans_head->next = tmp;
ans_head = tmp;
tmp1 = tmp1->next;
tmp2 = tmp2->next;
}
}
if(tmp1) ans_head->next = tmp1;
if(tmp2) ans_head->next = tmp2;
puts("答案为:");
ans_head = ans->next;
while(ans_head){
if(ans_head->a) printf("%d %d ",ans_head->a, ans_head->x);
ans_head = ans_head->next;
}
return 0;
}
|