基于visual Studio2013解决C语言竞赛题之1091多项式

来源:互联网 发布:社会主义 知乎 编辑:程序博客网 时间:2024/05/22 00:27






题目


解决代码及点评

/************************************************************************//* 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 +3x5   9            -9  8            5   6           3   1      *//************************************************************************/#include <stdio.h>#include <stdlib.h>#include <math.h>#include <string.h>typedef structstudent STU;struct student{int coef;int exp;struct student * next;};STU * Init91(){STU * p=(STU *)malloc(sizeof(STU));if (p==NULL){return NULL;}elsep->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;}}voidDeleteNode91(STU* pre,STU *cur){pre->next=cur->next;free(cur);}voidprintfNodes91(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.csdn.net/detail/yincheng01/6681845

解压密码:c.itcast.cn





0 0
原创粉丝点击