6-3-Add Two Polynomials-函数题

6-3-Add Two Polynomials-函数题

解题代码

Polynomial Add(Polynomial a, Polynomial b) {
	Polynomial add = (Polynomial)malloc(sizeof(struct Node));
	Polynomial ret = add;
	add->Next = NULL;
	Polynomial aa = a->Next, bb = b->Next;
	while (aa&&bb) {
		if (aa->Exponent > bb->Exponent) {
			Polynomial temp = (Polynomial)malloc(sizeof(struct Node));
			temp->Exponent = aa->Exponent;
			temp->Coefficient = aa->Coefficient;
			temp->Next = NULL;
			add->Next = temp;
			add = temp;
			aa = aa->Next;
		}
		else if (bb->Exponent > aa->Exponent) {
			Polynomial temp = (Polynomial)malloc(sizeof(struct Node));
			temp->Exponent = bb->Exponent;
			temp->Coefficient = bb->Coefficient;
			temp->Next = NULL;
			add->Next = temp;
			add = temp;
			bb = bb->Next;
		}
		else {
			if (bb->Coefficient + aa->Coefficient) {
				Polynomial temp = (Polynomial)malloc(sizeof(struct Node));
				temp->Exponent = aa->Exponent;
				temp->Coefficient = bb->Coefficient + aa->Coefficient;
				temp->Next = NULL;
				add->Next = temp;
				add = temp;
				aa = aa->Next;
				bb = bb->Next;
			}
			else {
				aa = aa->Next;
				bb = bb->Next;
			}
		}
	}
	while (aa) {
		Polynomial temp = (Polynomial)malloc(sizeof(struct Node));
		temp->Exponent = aa->Exponent;
		temp->Coefficient = aa->Coefficient;
		temp->Next = NULL;
		add->Next = temp;
		add = temp;
		aa = aa->Next;
	}
	while (bb) {
		Polynomial temp = (Polynomial)malloc(sizeof(struct Node));
		temp->Exponent = bb->Exponent;
		temp->Coefficient = bb->Coefficient;
		temp->Next = NULL;
		add->Next = temp;
		add = temp;
		bb = bb->Next;
	}
	return ret;
}

测试结果

在这里插入图片描述

问题整理

1.注意指数相同、系数相加为零的情况。
发布了47 篇原创文章 · 获赞 2 · 访问量 1336

猜你喜欢

转载自blog.csdn.net/Aruasg/article/details/105157895