题目 1679: 数据结构-一元多项式加法

这篇博客介绍了如何使用链表数据结构实现一元多项式的加法,包括读取输入、创建链表节点、比较与合并多项式、以及输出结果。代码示例中给出了针对两个多项式进行加法运算的过程,但博主在测试过程中遇到了问题,无法得到预期的正确结果。博客探讨了可能存在的错误和解决思路。
摘要由CSDN通过智能技术生成

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;
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值