数据结构作业_两个一次多项式相加

一次多项式相加

1.建表

struct node { //建表

	int num;
	int cishu;
	struct node*link;

};

2.输入函数

struct node*creat(int n)//建立一个指数项为n的多项式
{
	int Num, Ci;//输入头结点的数据
	cin >> Num >> Ci;
	struct node*head = new struct node;
	head->num = Num;
	head->cishu = Ci;
	head->link = 0;
	struct node*q = new struct node;
	q = head;
	int i;
	for (i = 1; i < n; i++)
	{
		struct node*p = new struct node;
		cin >> Num >> Ci;
		p->num = Num;
		p->cishu = Ci;
		p->link = 0;
		q->link = p;
		q = q->link;
	}
	return head;//多项式链表建好后返回头结点
}

3.选择排序函数(次数从高到低)

void SelectSort(struct node *head)//选择排序函数
{

	struct node* p, *q, *large;
	int temp;
	for (p = head; p->link != NULL; p = p->link)
	{
		large = p;
		for (q = p->link; q; q = q->link)
		{
			if (q->cishu > large->cishu)
			{
				large = q;
			}
		}
		if (large != p)
		{
			temp = p->cishu;
			p->cishu = large->cishu;
			large->cishu = temp;
		}
	}
}

4.整理成标准格式

void input(node*head)
{
	struct node*p = head;
	while (p)
	{
		cout << p->num << "x^" << p->cishu;
		if (p->link != 0)
		{
			cout << "+";
		}
		else {
			break;
		}
		p = p->link;
	}
	cout << endl;
}  //整理多项式的形式

5.多项式相加

struct node *merge(node *head1, node*head2)
{
	struct node*p1, *p2, *p3, *temp = 0;
	while (head1 != 0 && head2 != 0) {

		if (head1->cishu > head2->cishu)
		{
			p1 = head1;
			head1 = head1->link;
			p1->link = 0;
		}
		else
		{
			if (head2->cishu > head1->cishu)
			{
				p1 = head2;
				head2 = head2->link;
				p1->link = 0;
			}
			else
			{
				if (head1->num + head2->num == 0)
				{
					p2 = head1;
					head1 = head1->link;
					delete p2;
					p2 = head2;
					head2 = head2->link;
					delete p2;
					p2 = 0;
				}
				else
				{
					p1 = head1;
					head1 = head1->link;
					p1->num = p1->num + head2->num;
					p1->link = 0;
					p3 = head2;
					head2 = head2->link;
					delete p3;

				}
			}
		}
		if (p1 != 0)
		{
			if (temp == 0)
			{
				temp = p1;
				p2 = p1;
			}
			else
			{
				p2->link = p1;
				p2 = p2->link;
			}
		}
	}
	if (head1 != 0)
	{
		p2->link = head1;
	}
	if (head2 != 0)
	{
		p2->link = head2;
	}
	return temp;
}

6.主函数部分

int main()
{
	int a, b;
	cout << "请输入两个多项式的指数项个数:";
	cin >> a;
	cin >> b;
	node*head1 = creat(a);
	SelectSort(head1);
	cout << "您的第一个多项式是:" << endl;
	input(head1);
	node*head2 = creat(b);
	SelectSort(head2);
	cout << "您的第二个多项式是:" << endl;
	input(head2);
	node*output = merge(head1, head2);
	cout << "相加的结果为:" << endl;
	input(output);
	return 0;
}

7.头文件

#include<stdio.h>
#include<iostream>
#include<stdlib.h>

using namespace std;

运行这段代码,会报本地变量p1,p2没有初始化的错误,需要在项目->视图->属性管理器里面把SDL检查改为“否”就能正常运行了

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值