poly.h
#ifndef _POLY_H_
#define _POLY_H_
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
//结点结构
typedef struct Polynode
{
int coef;
int exp;
struct Polynode * next;
}Polynode,* Polylist;
//多项式约定为降次 指数为0时结束
//尾插法建立多项式
Polylist polycreate();
//多项式加法
void polyadd(Polylist polya,Polylist polyb);
#endif
poly.c
#include "poly.h"
//尾插法建立多项式
Polylist polycreate()
{
Polynode * head,* rear,* s;
int c, e;
//建立头结点
head = (Polynode *)malloc(sizeof(Polynode));
//rear指向链尾
rear = head;
//系数和指数
scanf("%d %d",&c,&e);
while(c != 0)
{
//建立新的结点
s = (Polynode *)malloc(sizeof(Polylist));
s->coef = c;
s->exp = e;
//表尾插入
rear->next = s;
rear = s;
printf("get\n");
scanf("%d %d",&c,&e);
}
rear->next = NULL;
return head;
}
//多项式加法
void polyadd(Polylist polya,Polylist polyb)
{
Polynode *p,*q,*pre,*temp;
int sum;
p = polya->next;
q = polyb->next;
pre = polya;
while((p != NULL) && (q != NULL))
{
if(p->exp < p->exp)
{
//将结点移动到A表中
pre->next = p;
pre = pre->next;
p = p->next;
}
else if(p->exp == q->exp)
{
//对应系数相加
sum = p->coef+q->coef;
if(sum != 0)
{
//系数不为零,替换对应结点
p->coef = sum;
pre -> next = p;
pre = pre->next;
p = p->next;
//删除结点
temp = q;
q = q->next;
free(temp);
}
else
{
//删除结点p,q移向下一结点
temp = p->next;
free(p);
p = temp;
temp = q->next;
free(q);
q = temp;
}
}
else
{
//将q结点加入和多项式中
pre->next = q;
pre = pre->next;
q = q -> next;
}
}
//表长度不等
if(p != NULL)
pre->next = p;
else
pre->next = q;
}
test.c
//测试用
#include"poly.h"
//显示表
void showpoly(Polylist p)
{
Polylist a = p->next;
while(a != NULL && a->coef != 0)
{
printf("%d %d\n",a->coef,a->exp);
a = a->next;
}
}
int main(void)
{
Polylist A;
Polylist B;
//建立一个表
A = polycreate();
showpoly(A);
printf("\n");
B = polycreate();
showpoly(B);
printf("\n");
polyadd(A,B);
showpoly(A);
return 0;
}
本文介绍如何使用C语言实现一元多项式的相加操作。通过讲解头文件`poly.h`的设计,源代码文件`poly.c`的实现以及测试文件`test.c`中的用例,详细阐述了数据结构在解决数学问题中的应用。
4612

被折叠的 条评论
为什么被折叠?



