dotcpp上的一道题,求高人指点,我写的代码一直显示错误0,可是我能想到的测试案例都想了,结果还是不行,求指点>﹏<>﹏<>﹏<
题目描述
让我们重温小学初中时那些一元多项式的加法吧,不同的是现在使用计算机来帮我们计算了。多年前不想写作业的梦想终于快要实现了!下面就给出书上的算法。
图:链表实现一元多项式加法
输入格式
输入数据包含多组测试数据,每组数据包含两行一元多项式。每个多项式包含若干对整数,每对整数的第一个是系数,第二个是指数。每个多项式不超过100项,整数间用空格隔开,并且指数是递减的。
输出格式
每组测试数据输出一行结果,每个整数后面空一格。(包括行尾)
样例输入
复制
3 2 4 1 7 0 2 4 1 1 2 3 1 4 3 2 4 1 7 0 2 4 -4 1
样例输出
复制
2 4 3 2 5 1 7 0 1 4 2 3 2 4 3 2 7 0
#include<stdio.h>
#include<stdlib.h>
typedef struct LN{
int coeft;//系数
int index;//指数
struct LN *next;
}*ln,LN;
ln creat(int,int);
void show(ln);
ln compare(ln,ln);
void destroy(ln,ln);
int main(){
ln heada=(ln)malloc(sizeof(LN));
ln headb=(ln)malloc(sizeof(LN));
heada->next=NULL;
headb->next=NULL;
int a,b;
int count=0;//count计数目前有几个回车
ln p=heada;
ln q;
ln l=headb;
char c;
while(scanf("%d %d",&a,&b)!=EOF){
if(count==0){
q=creat(a,b);
p->next=q;
p=q;
}
if(count==1){
q=creat(a,b);
l->next=q;
l=q;
}
if(getchar()=='\n'){
count++;
if(count==2){
show(compare(heada,headb));
destroy(heada,headb);
p=heada;
l=headb;
count=0;
}
}
}
}
ln creat(int a,int b){//生成一个结点
ln p=(ln)malloc(sizeof(LN));
p->next=NULL;
p->coeft=a;
p->index=b;
return p;
}
void show(ln head){//打印链表内所有元素
ln p=head->next;
while(p){
printf("%d %d ",p->coeft,p->index);
p=p->next;
}
printf("\n");
}
ln compare(ln heada,ln headb){//比较
ln p=heada->next;
ln q=headb->next;
ln l;
ln k=(ln)malloc(sizeof(LN));//k指向排序后的链表
k->next=NULL;
ln j=k;
while(p&&q){//利用归并
if((p->index)>(q->index)){
l=creat(p->coeft,p->index);
k->next=l;
k=l;
p=p->next;
}
else if((p->index)==(q->index)){
if((p->coeft)+(q->coeft)==0){
p=p->next;
q=q->next;
}
else{
l=creat((p->coeft)+(q->coeft),p->index);
k->next=l;
k=l;
p=p->next;
q=q->next;
}
}
else{
l=creat(q->coeft,q->index);
k->next=l;
k=l;
q=q->next;
}
}
if(q==NULL){
while(p){
l=creat(p->coeft,p->index);
k->next=l;
k=l;
p=p->next;
}
}
if(p==NULL){
while(q){
l=creat(q->coeft,q->index);
k->next=l;
k=l;
q=q->next;
}
}
return j;
}
void destroy(ln heada,ln headb){//清空链表
ln p=heada->next;
ln q;
while(p){
q=p;
p=p->next;
free(q);
}
heada->next=NULL;
ln l=headb->next;
while(l){
q=l;
l=l->next;
free(q);
}
headb->next=NULL;
}