1. 程式人生 > >【資料結構】【多項式連結串列實現相加】

【資料結構】【多項式連結串列實現相加】

#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