单链表表示多项式ADT&多项式加法

//多项式ADT
//利用单链表实现

//要求:输入顺序必须按照从指数的大小,由大到小
//如:7x^3+4x^2+1
//想要结束该次多项式输入,请在下一项输入 0 -1

#include<stdlib.h>
#include<iostream>
typedef struct node *ptrNode;
#define Len sizeof(struct node)
struct node
{
	int coefficient;
	int exponent;
	ptrNode next;
};

typedef ptrNode polynomial;

int max(const int x,const int y)
{
	if (x >= y)
		return x;
	else
		return y;
}

//找到最高指数项
polynomial find(polynomial poly)
{
	polynomial p = poly;
	if (p->next == nullptr)
		return p;
	else
	{
		do
		{
			p = p->next;
		} while (p->next!=nullptr);
		return p;
	}

}

//逆向计算出sum
polynomial add(polynomial poly1, polynomial poly2)
{
	polynomial p1 = poly1; polynomial p2 = poly2;
	polynomial head=nullptr,p;
	int max_expo = max((find(p1)->exponent), (find(p2)->exponent));
	p = (polynomial)malloc(Len);
	p->next = nullptr;
	p->exponent = 0;
	while (p->exponent<=max_expo)
	{
		if (p1 == nullptr && p2 == nullptr) break;
		if ((p1 != nullptr) && (p2 != nullptr))
		{
			if (p1->exponent == p2->exponent)
			{
				p->exponent = p1->exponent;
				p->coefficient = p1->coefficient + p2->coefficient;
				head = p;
				p1 = p1->next;
				p2 = p2->next;
			}
			else if (p1->exponent<p2->exponent)
			{
				p->exponent = p1->exponent;
				p->coefficient = p1->coefficient;
				head = p;
				p1 = p1->next;
			}
			else
			{
				p->exponent = p2->exponent;
				p->coefficient = p2->coefficient;
				head = p;
				p2 = p2->next;
			}
		}
		else if (p1 == nullptr)
		{
			p->exponent = p2->exponent;
			p->coefficient = p2->coefficient;
			head = p;
			p2 = p2->next;
		}
		else
		{
			p->exponent = p1->exponent;
			p->coefficient = p1->coefficient;
			head = p;
			p1 = p1->next;
		}


		p = (polynomial)malloc(Len);
		p->next = head;
	}
	return head;
}

//倒挂式建立链表
polynomial create()
{
	polynomial head, p1;
	p1 = (polynomial)malloc(Len);
	std::cout << "第1项:(如3x^4,输入3 4)" << std::endl;
	std::cin >> p1->coefficient >> p1->exponent;
	p1->next = nullptr;
	head = p1;
	int n = 1;
	while (p1->exponent != -1)
	{
		p1 = (polynomial)malloc(Len);
		p1->next = head;
		std::cout <<"第"<<++n<<"项:"<< std::endl;
		std::cin >> p1->coefficient >> p1->exponent;
		head = p1;
	}
	return head->next;
}
void print(polynomial poly)
{
	polynomial p= poly;
	while ((p->next)!= nullptr)
	{
		std::cout << p->coefficient << "x^" << p->exponent << "+";
		p = p->next;
	}
	std::cout << p->coefficient << "x^" << p->exponent;
}

int main()
{
	std::cout << "请输入第1个表达式:(0 -1结束)" << std::endl;
	polynomial poly1 = create();
	std::cout << "请输入第2个表达式:" << std::endl;
	polynomial poly2 = create();
	polynomial polySum=add(poly1, poly2);
	std::cout << "the sum=";
	print(polySum);
	std::cout << std::endl;
	return 0;
}


使用单链表编的多项式,因为语言掌握不好,C和Cpp混用。另外输入的格式要求严格,没检查特殊情况是否正确。

学习单链表的一个例子,供参考。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值