【数据结构】【多项式链表实现相加】

#include<bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1006;

struct node {
	double coef;
	int exp;
	struct node*next;
};

struct node*Add(struct node *head1, struct node *head2) {
	struct node *anshead = (struct node *)malloc(sizeof(struct node));
	struct node *p = (struct node *)malloc(sizeof(struct node));
	struct node *r1 = (struct node *)malloc(sizeof(struct node));
	struct node *r2 = (struct node *)malloc(sizeof(struct node));
	p = anshead;
	r1 = head1->next;
	r2 = head2->next;
	while (r1 != NULL && r2 != NULL) {
		struct node *tmp = (struct node *)malloc(sizeof(struct node));
		tmp->next = NULL;
		if (r1->exp == r2->exp) {
			tmp->exp = r1->exp;
			tmp->coef = r1->coef + r2->coef;
			r1 = r1->next;
			r2 = r2->next;
		}
		else if (r1->exp < r2->exp) {
			tmp->exp = r2->exp;
			tmp->coef = r2->coef;
			r2 = r2->next;
		}
		else {
			tmp->exp = r1->exp;
			tmp->coef = r1->coef;
			r1 = r1->next;
		}
		p->next = tmp;
		p = p->next;
	}
	return anshead;
}

int main(){
	struct node*head1 = (struct node *)malloc(sizeof(struct node));
	head1->next = NULL;
	struct node*r1 = (struct node *)malloc(sizeof(struct node));
	r1 = head1;

	struct node*head2 = (struct node *)malloc(sizeof(struct node));
	head2->next = NULL;
	struct node*r2 = (struct node *)malloc(sizeof(struct node));
	r2 = head2;

	int n1, n2;
	printf("输入第一个多项式项数:\n");
	scanf("%d", &n1);
	printf("输入第一个多项式系数和系数:\n");
	for (int i = 0; i<n1; i++){
		struct node*tmp = (struct node *)malloc(sizeof(struct node));
		tmp->next = NULL;
		scanf("%lf%d", &tmp->coef, &tmp->exp);
		r1->next = tmp;
		r1 = tmp;
	}
	printf("输入第二个多项式项数:\n");
	scanf("%d", &n2);
	printf("输入第二个多项式系数和指数:\n");
	for (int i = 0; i<n2; i++){
		struct node*tmp = (struct node *)malloc(sizeof(struct node));
		tmp->next = NULL;
		scanf("%lf%d", &tmp->coef, &tmp->exp);
		r2->next = tmp;
		r2 = tmp;
	}
	struct node *ans = (struct node *)malloc(sizeof(struct node));
	ans = Add(head1, head2);
	struct node*p = (struct node *)malloc(sizeof(struct node));
	p = ans->next;
	printf("两个多项式相加的多项式为:\n");
	int flag = 0;
	while (p) {
		
		if (p->coef == 0);
		else {
			if(flag)printf("+"); flag = 1;
			if (p->exp == 0)printf("%f", p->coef);
			else if (p->exp == 1)printf("%fx", p->coef);
			else printf("%fx^%d ", p->coef, p->exp);
		}
		p = p->next;
	}
	printf("\n");
}
//3
//3 20 2 5 4 0
//4
//3 4 2 3 3 2 1 0

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值