PAT 1002. A+B for Polynomials
This time, you are supposed to find A+B where A and B are two polynomials.
Input
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 (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.
Output
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.22 2 1.5 1 0.5
Sample Output
3 2 1.5 1 2.9 0 3.2
代码如下(复杂的链表)
#includeusing namespace std;struct node{ int exp; double coe; node* next;};int main(){ int N,cnt=0; cin>>N; node* l1=new node(); node* ptr1=l1; for(int i=0;i next=NULL; cin>>lnode->exp>>lnode->coe; ptr1->next=lnode; ptr1=ptr1->next; } cin>>N; node* l2=new node(); node* ptr2=l2; for(int i=0;i >lnode->exp>>lnode->coe; lnode->next=NULL; ptr2->next=lnode; ptr2=ptr2->next; } ptr1=l1->next; ptr2=l2->next; node* l=new node(); node* ptr=l; while(ptr1!=NULL&&ptr2!=NULL){ if(ptr1->exp>ptr2->exp){ if(ptr1->coe!=0) cnt++; ptr->next=ptr1; ptr=ptr->next; ptr1=ptr1->next; } else if(ptr1->exp exp){ if(ptr2->coe!=0) cnt++; ptr->next=ptr2; ptr=ptr->next; ptr2=ptr2->next; }else{ ptr1->coe+=ptr2->coe; if(ptr1->coe!=0) cnt++; ptr->next=ptr1; ptr=ptr->next; ptr1=ptr1->next; ptr2=ptr2->next; } } while(ptr1!=NULL){ if(ptr1->coe!=0) cnt++; ptr->next=ptr1; ptr=ptr->next; ptr1=ptr1->next; } while(ptr2!=NULL){ if(ptr2->coe!=0) cnt++; ptr->next=ptr2; ptr=ptr->next; ptr2=ptr2->next; } ptr=l->next; cout< coe!=0) printf(" %d %.1f",ptr->exp,ptr->coe); ptr=ptr->next; }}
分析
其实用其他容器都可以很好的解决这个问题,vector,map等等;下面附上我的另一种解法
代码如下
#include#include