使用单链表实现稀疏多项式的加法

下面直接是代码,话不多说:

#include<stdio.h>
#include<stdlib.h>

typedef struct _node
{
	int coefficiet;//系数
	int index;//指数
	struct _node* next;
}Node,*pNode;

pNode creat_link(void);//创建单链表并初始化
void output(pNode head);//输出链表的结果
pNode assign(pNode la, pNode lb);//系数多项式加法的实现
void destroy(pNode head);//销毁动态申请的空间


int main()
{
	pNode la, lb,lc;
	la = creat_link();
	output(la);
	printf("\n");
	lb = creat_link();
	output(lb);
	printf("\n");
	lc = assign(la, lb);
	output(lc);
	destroy(lc);

	return 0;
}

pNode creat_link(void)
{
	pNode head, p, s;
	head = p = (pNode)malloc(sizeof(Node));
	if (head == NULL)
		return 0;
	p->next = NULL;
	int coefficient, index;
	printf("请输入:coefficient--index(输入0代表结束)\n");
	scanf("%d%d", &coefficient,&index);
/*g(x)=3x+5x*x-8x*x*x+8x~2000-6x~10000
 f(x)=2+2x-4x*x+9x~4-8x~2000+12x~7500
*/
	while (coefficient != 0)
	{
		s = (pNode)malloc(sizeof(Node));
		if (s != NULL)
		{
			s->coefficiet = coefficient;
			s->index = index;
			s->next = p->next;
			p->next = s;
			p = s;
			scanf("%d%d", &coefficient, &index);
		}
		else
			return 0;
	}
	return head;
}
void destroy(pNode head)
{
	pNode p, q = head;
	while (q != NULL)
	{
		p = q;
		q = q->next;
		free(p);
	}
}


pNode assign(pNode la, pNode lb)
{
	pNode pa = la->next;
	pNode pb = lb->next;
	pNode lc,temp=NULL;
	pNode pc = lc = la;
	while (pa != NULL && pb != NULL)
	{
		if (pa->index <= pb->index)
		{
			if (pa->index == pb->index)
			{
				pa->coefficiet += pb->coefficiet;
				pc->next = pa;
				pc = pa;
				pa = pa->next;
				temp = pb;//中间变量将已经进行过加法的销毁
				pb = pb->next;
				free(temp);
			}
			else
			{
				pc->next = pa;
				pc = pa;
				pa = pa->next;
			}
		}
		else
		{
			pc->next = pb;
			pc = pb;
			pb = pb->next;
		}
	}
	pc->next = pa ? pa : pb;
	free(lb);
	return lc;
}

void output(pNode head)
{
	pNode p = head->next;
	while (p != NULL)
	{
		printf(" %dx~%d ", p->coefficiet, p->index);
		p = p->next;
	}
}

可以根据这两张图来帮助理解:

 

 

 

 

代码结果:

 

在这里试验是对的,也不知道还有什么bug。

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值