PAT甲级1002 A+B for Polynomials (25分)附测试点6段错误原因
This time, you are supposed to find A+B where A and B are two polynomials.
Input Specification:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
K N1 aN1 N2 aN2 ... NK aNK
where K is the number of nonzero terms in the polynomial, Ni and aNi (,) are the exponents and coefficients, respectively. It is given that 1,0.
Output Specification:
For each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.
Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
3 2 1.5 1 2.9 0 3.2
这个题可以用链表写,也可以用哈希表写,用哈希会更简单一些,不过最近在看严老师的数据结构,里面专门有再讲多项式的加减,于是用链表重新写了一遍。
测试点6要求输出0,也就是多项式每一项相加减抵消了。
附代码:
#include <iostream> using namespace std; struct Node{ int expn;//表示指数 double coef;//表示系数 Node*next; }; void InitList(Node*L,int n){ for(int i=0;i<n;i++){ Node*a=(Node*)malloc(sizeof(Node)); cin>>a->expn>>a->coef; L->next=a; L=a; } L->next=NULL; } int main() { Node*La=(Node*)malloc(sizeof(Node)); Node*Lb=(Node*)malloc(sizeof(Node)); //La和Lb分表代表着两个链表 int n; cin>>n; InitList(La,n); cin>>n; InitList(Lb,n); Node*pa=La->next,*pb=Lb->next;//工作指针 Node*Lc=La,*pc=Lc;//用La的头结点作为Lc的头结点 while(pa&&pb){ if(pa->expn>pb->expn){ pc->next=pa; pc=pa; pa=pa->next; } else if(pa->expn<pb->expn){ pc->next=pb; pc=pb; pb=pb->next; } else if(pa->expn==pb->expn){ pa->coef+=pb->coef; if(pa->coef!=0.0){ pc->next=pa; pc=pa; } pa=pa->next; pb=pb->next; } } if(pa) pc->next=pa; else { pc->next=pb; } pc=Lc; int len=0; while(pc->next!=NULL){ len++; pc=pc->next; } cout<<len; pc=Lc->next; while(pc!=NULL){ printf(" %d %.1f",pc->expn,pc->coef); pc=pc->next; } return 0; }