一元多项式的加减乘除运算(c++实现)—数据结构学习

#include
#include
#include
using namespace std;
typedef struct Node* List;
struct Node
{	
	List next;//指向下一个结点
	int x;//指数
	int z;//系数
};
List Read()
{
	List L = new Node;
	List head = L;
	int n=0;
	cout << "请输入你的多项式的项数(项数不可以是0或者负数!)" << endl;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		int x, z;
		List temp = new Node;
		cout << "请输入第:" << i + 1 << "项指数" << endl;
		cin >> x;
		cout << "请输入第:" << i + 1 << "项系数" << endl;
		cin >> z;
		temp->x = x;
		temp->z = z;
		L->next = temp;
		L = L->next;

	}
	L->next = NULL;
	return head->next;//由头节点!
}


//加法运算
List Add(List L1,List L2)
{
	List add = new Node;
	add->next = NULL;
	List head = add;
	List t1 = L1;
	List t2 = L2;

	List temp;
	while (t1&&t2)//如果两个链表都不是空的时候
	{
		if (t1->x== t2->x)//指数相等
		{
			temp->z = t1->z + t2->z;
			temp->x = t1->x;
			t1 = t1->next;
			t2 = t2->next;
		}
		else if (t1->x > t2->x)
		{
			temp->x = t1->x;
			temp->z = t1->z;
			t1 = t1->next;
		}
		else if(t1->x < t2->x)
		{
			temp->x = t2->x;
			temp->z = t2->z;
			t2 = t2->next;
		}
		add->next = temp;
		add = add->next;
		
	}
	if (t1)
	{
		add->next =t1;
	}
	else if (t2)
	{
		add->next = t2;
	}
	
	return head->next;
}

//乘法运算
List Mul(List L1, List L2)
{
	List mul = new Node;
	mul->next = NULL;
	List head = mul;
	List t1 = L1;
	List t2 = L2;
	for (; t1; t1 = t1->next)
	{
		for (; t2; t2 = t2->next)
		{
			List temp = new Node;
			temp->x = t1->x + t2->x;//指数相加
			temp->z = t1->z * t2->z;//系数相乘
			head = Add(temp, mul);
			mul = head;//重新确定开头
		}
		return head;
	}
}

//遍历
void Show(List L)
{	
	List t = L;
	int falg = 0;
	for (; t; t = t->next)
	{
		if (!falg)
		{
			falg = 1;
		}
		else
		{
			cout << " " ;
			
		}
		cout << t->z << t->x;
	}

}

你可能感兴趣的:(数据结构与算法)