一元多项式相加

使用链表实现。


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

typedef struct node
{
	float p;
	unsigned int e;
	struct node *next;
}polynomial,*p_polynomial;

p_polynomial poly_add(p_polynomial a, p_polynomial b)
{
	p_polynomial p=a, q=b, t;
	/*存在性*/
	if (!a || !b)
	{
		printf("至少有一个多项式不存在,无法计算!");
		return(NULL);
	}
	while (p->next || q->next)
	{
		if (!p->next)
		{
			p->next = q->next;
			return(a);
		}
		if (!q->next)
		{
			return(a);
		}
		if (q->next->e == p->next->e)
		{
			p->next->p += q->next->p;
			p = p->next;
			q->next = q->next->next;
		}
		else
		{
			if (q->next->e < p->next->e)
			{
				t = q->next;
				q->next = t->next;
				t->next = p->next;
				p->next = t;
				p = p->next;
			}
			else
			{
				p = p->next;
				while (p->next)
				{
					if (q->next->e > p->next->e)
						p = p->next;
					else
						break;						
				}
				if (!p->next)
				{
					t = q->next;
					p->next->next = t;
					return(a);
				}
				else
					continue;
			}
		}
	}
}
int display_polynomial(p_polynomial p)
{
	if (!p)
	{
		printf("多项式不存在");
		return(0);
	}
	p_polynomial t = p->next;
	while (t)
	{
		printf("%f %d ", t->p, t->e);
			t = t->next;
	}
	printf("\n");
	return(1);
}

/*test*/
int main()
{
	const int n1 = 5;
	const int n2 = 7;
	p_polynomial h1 = (p_polynomial)malloc(sizeof(polynomial));
	p_polynomial h2 = (p_polynomial)malloc(sizeof(polynomial));
	h1->next = NULL;
	h2->next = NULL;
	p_polynomial t = h1;
	for (int i = 0; i < n1; i++)
	{
		t->next = (p_polynomial)malloc(sizeof(polynomial));
		t->next->e = i;
		t->next->p = i + 1; 
		t = t->next;
		t->next = NULL;
	}
	t->next = (p_polynomial)malloc(sizeof(polynomial));
	t->next->e =10;
	t->next->p = 3;
	t = t->next;
	t->next = NULL;

	t = h2;
	for (int i = 0; i < n2; i++)
	{
		t->next = (p_polynomial)malloc(sizeof(polynomial));
		t->next->e = i+3;
		t->next->p = i + 1;
		t = t->next;
		t->next = NULL;
	}

	display_polynomial(h1);
	display_polynomial(h2);

	display_polynomial(poly_add(h1, h2));

	while (true)
	{
	}

	return(1);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值