【数据结构】15 队列应用实例:多项式加法运算

多项式加法运算

我们准备采用不带头节点的单向链表结构表示一元多项式,并按照指数递减的顺序排列各项。

对列表存放的两个多项式进行加法运算时,可以使用两个指针p1和p2。初始时的p1和p2分别指向这两个多项式第1个节点(指数的最高项)。通过循环不断比较p1和p2所指的节点,比较结果为以下三种情况之一并作不同处理。

  1. 两数据项指数相等
    若结果不为0,将结果对应的系数连同指数一并存入结果多项式。沿着两结点的链域,使P1和P2分别指向两个多项式的下一项,再进行新一轮比较。
  2. P1中的数据项指数较大
    P2保持不变,把P1的当前项存入多项式,P1指向下一项。
  3. P2中的数据项指数较大
    P1保持不变,把P2的当前项存入多项式,P2指向下一项。

代码实现

c 复制代码
typedef struct PolyNode* PtrToPolyNode;
struct PolyNode {
	int Coef;
	int Expon;
	PtrToPolyNode Next;
};
typedef PtrToPolyNode Polynomial;

int compare(int e1, int e2) {
	if (e1 > e2) {
		return 1;
	}
	else if(e1 < e2)
	{
		return -1;
	}
	else
	{
		return 0;
	}
}


void Attach(int ceof, int expon, Polynomial* PtrRear) {
	Polynomial t;
	t->Expon = expon;
	t->Coef = ceof;
	t->Next = NULL;
	(*PtrRear)->Next = t;
	*PtrRear = t;
}

Polynomial PolyAdd(Polynomial P1, Polynomial P2) {
	Polynomial front, rear;
	rear = (Polynomial)malloc(sizeof(struct PolyNode));
	front = rear;
	while (P1 && P2) {
		switch (compare(P1->Expon, P2->Expon))
		{
		case 1:
			Attach(P1->Coef, P1->Expon, &rear);
			P1 = P1->Next;
			break;
		case -1:
			Attach(P2->Coef, P2->Expon, &rear);
			P2 = P2->Next;
			break;
		case 0:
			int sum = P1->Coef + P2->Coef;
			if (sum) {
				Attach(sum, P1->Expon, &rear);
				P1->Next;
				P2->Next;
				break;
			}

		}
	}

	for (; P1; P1 = P1->Next) {
		Attach(P1->Coef, P1->Expon, &rear);
	}
	for (; P2; P2 = P2->Next) {
		Attach(P2->Coef, P2->Expon, &rear);
	}
	rear->Next = NULL;
	Polynomial temp = front;
	front = front->Next;
	free(temp);
	return front;

}
相关推荐
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1231 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1121 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19432 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww2 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚2 天前
[数据结构] 排序
数据结构
睡不醒的kun2 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌2 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long2 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn2 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap