
题目
解决代码及点评
/************************************************************************/
/*
91. 建立两个链表,来表示x幂的两个多项式,链表中的结点有三个字段coef、exp和next,
分别表示多项式每项的系数、x的指数及指向下一项的指针。
编一程序,按x的降幂输入多项式的系数和指数,建立两个链表,
然后编一函数来完成把两个多项式的链表叠加到第三个链表中。例如:
第一个多项式为: -4x8 +5x6 +3x4 -4x的链表为:
-4 8 5 6 3 4 -4 1
第二个多项式为: 5x9 -5x8 -3x4 +7x的链表为:
5 9 -9 8 5 6 3 1
结果的多项式为: 5x9 -9x8 +5x6 +3x
5 9 -9 8 5 6 3 1
*/
/************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
typedef struct student STU;
struct student
{
int coef;
int exp;
struct student * next;
};
STU * Init91()
{
STU * p=(STU *)malloc(sizeof(STU));
if (p==NULL)
{
return NULL;
}
else
p->next=NULL;
return p;
}
STU * Insert91(STU * head,int coef,int exp)
{ STU * last=head;
if (last==NULL)
{
return NULL;
}
while(last->next!=NULL)
last=last->next;
STU *p=(STU *)malloc(sizeof(STU));
if (p==NULL)
{
return NULL;
}
else
{
p->coef=coef;
p->exp=exp;
last->next=p;
p->next=NULL;
return p;
}
}
void DeleteNode91(STU* pre,STU *cur)
{
pre->next=cur->next;
free(cur);
}
void printfNodes91(STU *head)
{
STU *p=head->next;
while(p!=NULL)
{
printf("%2d%2d",p->coef,p->exp);
printf("->");
p=p->next;
}
printf("\n");
}
STU * GB91(STU * A,STU * B)
{
STU *C=Init91();
STU *p1=A->next;
STU * tempA=A;
STU *tempB=B;
STU*p2=B->next;
STU *temp=NULL;
while(p2!=NULL&&p1!=NULL)
{
if (p1->exp>p2->exp)
{
temp=Insert91(C,p1->coef,p1->exp);
DeleteNode91(tempA,p1);
p1=tempA->next;
}
else if (p1->exp<p2->exp)
{
temp=Insert91(C,p2->coef,p2->exp);
DeleteNode91(tempB,p2);
p2=tempB->next;
}
else
{
if (p1->coef+p2->coef!=0)
{
temp=Insert91(C,p2->coef+p1->coef,p2->exp);
DeleteNode91(tempB,p2);
p2=tempB->next;
DeleteNode91(tempA,p1);
p1=tempA->next;
}
else
{
p1=p1->next;
tempA=tempA->next;
p2=p2->next;
tempB=tempB->next;
}
}
}
if (p2==NULL)
{
temp->next=p1;
}
else
{
temp->next=p2;
}
return C;
}
void main()
{
STU * A=Init91();
Insert91(A,-4,8);
Insert91(A,5,6);
Insert91(A,3,4);
Insert91(A,-4,1);
printfNodes91(A);
STU * B=Init91();
Insert91(B,5,9);
Insert91(B,-5,8);
Insert91(B,-3,4);
Insert91(B,7,1);
printfNodes91(B);
printfNodes91(GB91(A,B));
system("pause");
}
代码编译以及运行
由于资源上传太多,资源频道经常被锁定无法上传资源,同学们可以打开VS2013自己创建工程,步骤如下:
1)新建工程
2)选择工程
3)创建完工程如下图:
4)增加文件,右键点击项目
5)在弹出菜单里做以下选择
6)添加文件
7)拷贝代码与运行
程序运行结果
代码下载
http://download.youkuaiyun.com/detail/yincheng01/6681845
解压密码:c.itcast.cn