一、步骤描述
- 创建一个只有头结点的空链表。
- 循环n次执行以下操作:生成一个新节点*s;输入*s的数据域;设置一个前驱指针pre,用于指向待找到的第一个大于输入项指数的前驱,pre初值指向头结点;设置指针q指向首元结点;循链向下逐个寻找第一个大于输入项指数的节点*q,将输入节点*s插入到节点*q之前。
二、多项式数据结构
typedef struct PNode
{
float coef; //系数
int expn; //指数
struct PNode *next;
}PNode,*Polynomial;
三、算法描述
void CreatePolyn(Polynomial &P,int n)
{
P = new PNode; //头指针指向头结点
p->next = NULL;
for(i=0; i<n; i++)
{
s = new PNode;
enter s->coef&s->expn;
pre = p;
q = p->next;
while(q && q->expn < s->expn)
{//寻找*s结点插入位置
pre = q;
q = q->next;
}
s->next = q;
pre->next = s;
}
}
四、C语言实现代码
#include <stdio.h>
typedef struct PNode
{
float coef; //系数
int expn; //指数
struct PNode *next;
}PNode,*Polynomial;
int CreatPolyn(Polynomial &p,int n)
{//创建多项式
p=new PNode; //头结点
p->next = NULL;
int i;
PNode *s,*pre,*q;
printf("enter coef & expn:",n);
for(i=1;i<=n;i++)
{
s=new PNode;
scanf("%f %d",&s->coef,&s->expn);
pre=p;
q=p->next;
while(q && q->expn<s->expn)
{//寻找结点插入位置
pre=q;
q=q->next;
}
s->next=q;
pre->next=s;
}
return 1;
}
int AddPolyn(Polynomial &pa,Polynomial &pb)
{//多项式相加
PNode *p1,*p2,*pc,*r;
p1=pa->next;
p2=pb->next;
pc = pa;
float sum;
while(p1 && p1)
{
if(p1->expn == p2->expn)
{//指数相同,系数相加
sum = p1->coef +p2->coef;
if(sum !=0)
{
p1->coef =sum;
pc->next =p1;
pc =p1;
p1=p1->next;
r =p2;
p2=p2->next;
delete r; //释放不使用结点,避免造成漏洞
}
else
{
r=p1; p1=p1->next; delete r;
r=p2; p2=p2->next; delete r;
}
}
else if(p1->expn<p2->expn)
{
pc->next = p1;
pc = p1;
p1 = p1->next;
}
else
{
pc->next = p2;
pc = p2;
p2 = p2->next;
}
}
pc->next = p1?p1:p2;
delete p2;
return 1;
}
int main()
{
Polynomial pa,pb,pc;
PNode *temp;//中间指针,用于输出值
int a,b;
printf("enter pa & pb number of expn:\n");
scanf("%d %d",&a,&b);
CreatPolyn(pa,a);CreatPolyn(pb,b);
printf("you enter pa is:");
temp = pa->next;
while(temp)
{
printf("%f*10^%d",temp->coef,temp->expn);
if(temp->next) printf(" + ");
temp = temp->next;
}
printf("\nyou enter pb is:");
temp = pb->next;
while(temp)
{
printf("%f*10^%d",temp->coef,temp->expn);
if(temp->next) printf(" + ");
temp = temp->next;
}
AddPolyn(pa,pb);
printf("\npa + pb =");
temp = pa->next;
while(temp)
{
printf("%f*10^%d",temp->coef,temp->expn);
if(temp->next) printf(" + ");
temp = temp->next;
}
return 1;
}