链表实现多项式的加法
poly.h
#ifndef POLYNOMIALCOMPUTE_POLY_H
#define POLYNOMIALCOMPUTE_POLY_H
struct PolyNode;
typedef struct PolyNode *Polynomial;
void Attach(int c, int e, Polynomial *pRear);
Polynomial PolyAdd(Polynomial P1, Polynomial P2);
void PrintPoly(Polynomial P);
void TestPoly();
#endif //POLYNOMIALCOMPUTE_POLY_H
poly.c
#include "poly.h"
#include <malloc.h>
#include <stdlib.h>
#include <stdio.h>
struct PolyNode {
Polynomial link; // 指向下一个节点的位置
int expon; // 指数,英文是 exponent
int coef; // 系数,英文是 coefficient
};
// 新增一个节点
void Attach(int c, int e, Polynomial *pRear)
{
Polynomial P;
P = (Polynomial)malloc(sizeof(struct PolyNode)); // 分配空间
P->coef = c; // 对新节点赋值
P->expon = e;
P->link = NULL;
(*pRear)->link = P; // 尾节点指向P
*pRear = P; // 修改 pRear 值
}
int Compare(int Lhs, int Rhs)
{
return Lhs - Rhs;
}
Polynomial PolyAdd(Polynomial P1, Polynomial P2)
{
Polynomial front, rear, temp;
int sum;
rear = (Polynomial)malloc(sizeof(struct PolyNode));
front = rear; // 由 front 记录结果多项式链表头节点
while (P1 && P2)
{ // 当两个多项式都有非零项待处理时
switch (Compare(P1->expon, P2->expon))
{
case 1:
Attach(P1->coef, P1->expon, &rear);
P1 = P1->link;
break;
case -1:
Attach(P2->coef, P2->expon, &rear);
P2 = P2->link;
break;
case 0:
sum = P1->coef + P2->coef;
if (sum) Attach(sum, P1->expon, &rear);
P1 = P1->link;
P2 = P2->link;
break;
}
}
// 将未处理完的另一个多项式的所有节点依次复制到结果多项式中去
for(; P1; P1 = P1->link) Attach(P1->coef, P1->expon, &rear);
for(; P2; P2 = P2->link) Attach(P2->coef, P2->expon, &rear);
rear->link = NULL;
temp = front;
front = front->link; // 令 front 指向结果多项式的第一个非零项
free(temp); // 释放临时空表头节点
return front;
}
void PrintPoly(Polynomial P)
{
Polynomial tmp = P;
for(; tmp; tmp = tmp->link)
{
printf("%d %d ", tmp->coef, tmp->expon);
}
}
void TestPoly()
{
int P1Coef[5] = {3, 4, -1, 2, -1};
int P1expon[5] = {5, 4, 3, 1, 0};
int P2Coef[4] = {2, 1, -7, 1};;
int P2expon[4] = {4, 3, 2, 1};
Polynomial P1, P2;
P1 = (Polynomial)malloc(sizeof(struct PolyNode));
P2 = (Polynomial)malloc(sizeof(struct PolyNode));
Polynomial P1Rear;
P1Rear = P1;
Polynomial P2Rear;
P2Rear = P2;
for (int i = 0; i < 5; ++i)
{
Attach(P1Coef[i], P1expon[i], &P1Rear); // 注意这里传的是地址!!!
}
P1 = P1->link; // 因为第一个节点没有存储数据,所以 P1 要往后挪一位
for (int i = 0; i < 4; ++i)
{
Attach(P2Coef[i], P2expon[i], &P2Rear);
}
P2 = P2->link;
Polynomial res = PolyAdd(P1, P2);
PrintPoly(P1);
printf("\n");
PrintPoly(P2);
printf("\n");
PrintPoly(res);
}
main.c(测试函数)
#include "poly.h"
// 测试函数
int main()
{
TestPoly();
return 0;
}
测试:
测试样例:
测试结果: