/*测试样例,第一个数字表示参数个数
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
*/
#include<iostream>
#include<malloc.h>//申请空间需要头文件
#define NULL 0
using namespace std;
typedef struct node {
int coef;//系数
int exp;//指数
node* next;//指向下一个结点
}list;//别名
/*遍历链表的函数*/
node* newNode(int c, int e) {
node* temp = (node*)malloc(sizeof(struct node));//申请结点
temp->coef = c;//设定系数和指数
temp->exp = e;
temp->next = NULL;//指针域置空
return temp;//返回新生成的指针
}
/*把两个一元多项式放入到链表中去,操作如下*/
list* createPoly(int n)//n为结点的个数,
{
list* L = NULL;//头指针L先为空
if (n == 0) {//什么也没有输入进来。
return L;
}
else {
//申请了一个头节点,L作为头指针。
L = (list*)malloc(sizeof(struct node));
}
int ac = 0;//输入数据的系数和指数
int ae = 0;
node* lastp = L;//定义一个指向当前链表最后一个结点的指针。
node* temp = NULL;//临时指针先置空
for (int i = 0; i < n; i++)
{//将后面的结点一个一个插入到里面
cin >> ac >> ae;
temp = newNode(ac, ae);//将两个参数储存到临时结点中
//尾插法建立链表
lastp->next = temp;//把最后一个结点的指针域指向当前新生成的结点。
lastp = temp;
}
return L;//返回头指针L
}
/*两个链表的相加函数*/
list* addPoly(list* A, list* B) {
if (!A->next) return A;//只有一个头结点,其余为空
if (!B->next) return B;
node* pa = A->next;//遍历两个链表,并初始化指向链表头结点后的第一个结点。
node* pb = B->next;
//为相加函数定义头结点,并用malloc函数申请
list* sum = (list*)malloc(sizeof(struct node));
sum->next = NULL;//头结点置空
node* lastp = sum;//同样尾插法,定义结点指向最后一个结点
node* temp = NULL;
while (pa && pb)//开始运算,要保证两个多项式链表都不为空,即没有遍历结束
{
if (pa->exp == pb->exp) //指数相等
{
if ((pa->coef + pb->coef) != 0) //系数相加是否为0
{
//新建结点,一个放置系数,另一个是指数,pa,pb指数相等,放入其中一个
temp = newNode(pa->coef + pb->coef, pa->exp);
//尾插法输入结点
lastp->next = temp;
lastp = temp;
}
pa = pa->next;//指针后移
pb = pb->next;
}
else if (pa->exp > pb->exp) //指数不等
{
temp = newNode(pa->coef, pa->exp);
lastp->next = temp;
lastp = temp;
pa = pa->next;
}
else
{
temp = newNode(pb->coef, pb->exp);
lastp->next = temp;
lastp = temp;
pb = pb->next;
}
}
if (pa == NULL && pb != NULL) //有一方遍历结束
{
lastp->next = pb;
}
if (pb == NULL && pa != NULL)
{
lastp->next = pa;
}
return sum;
}
/*打印链表每个结点数据*/
void printPoly(list* L) //传进去一个指向头指针List的链表
{
if (!L->next)//判断头结点的地址域是否为空
{
cout << "0 0 ";
}
else
{
node* p = L->next;//链表不为空时,第一个结点的指针
int i = 0;
while (p)//一个循环,当链表里还有数据时,可以不断循环输出
{
if (i == 0)//第一次输出数据时,前面不需要空格
{
cout << p->coef << " " << p->exp;
i++;
}
else {
cout << " " << p->coef << " " << p->exp;
}
p = p->next;//每输出完一次数据,p后移一位
}
}
}
int main(void) {
int n, m;//把每一行的第一个数据放进去
cin >> n;
list* La = createPoly(n);//调用函数创建链表
cin >> m;
list* Lb = createPoly(m);
list* result = addPoly(La, Lb);//结果链表头指针用函数实现,储存多项式相加结果
printPoly(result);//直接打印结果
return 0;
}
代码呈现如下——