一次多项式相加
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检查改为“否”就能正常运行了