題目連接:http://www.patest.cn/contests/pat-a-practise/1002node
題目很簡單,求兩個多項式相加的結果,一開始ZS用數據結構裏的鏈表去敲,只對兩組數據,怎麼也找不到錯誤,後來果斷換成數組模擬,一次AC,但仍是沒想明白鏈表哪錯了!ios
數組模擬AC代碼:數組
#include <iostream> #include <iomanip> #include <cstring> using namespace std; int main() { double a[1100],b[1100],va; int sum,n,temp; while (cin>>n) { memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); sum=n; while (n--) { cin>>temp>>va; a[temp]=va; } cin>>n; sum+=n; while(n--) { cin>>temp>>va; b[temp]=va; if (a[temp]==(-b[temp])) { sum-=2; a[temp]=0; } else { if (a[temp]!=0) sum--; a[temp]+=b[temp]; } } cout <<sum; for (int i=1000;i>=0;i--) if(a[i]!=0) cout <<" "<<i<<" "<<fixed<<setprecision(1)<<a[i]; cout <<endl; } return 0; }
鏈表wa代碼,哪位大神能幫我看看,不勝感激:數據結構
#include <iostream> #include <cstring> #include <iomanip> using namespace std; struct node { double coef; int exp; node *next; }; node *listcreat() { int n; cin>>n; node *head,*rear,*s; double c; int e; head=(node *)malloc(sizeof(node)); head->exp=n; rear=head; while (n--) { cin>>e>>c; s=(node *)malloc(sizeof(node)); s->exp=e; s->coef=c; rear->next=s; rear=s; } rear->next=NULL; return head; } node *add(node *x,node *y) { x->exp=x->exp+y->exp; node *p,*q,*tail,*temp; double sum; p=x->next; q=y->next; tail=x; while (p!=NULL&&q!=NULL) { if (p->exp>q->exp) { tail->next=p; tail=p; p=p->next; } else if (p->exp<q->exp) { tail->next=q; tail=q; q=q->next; } else { if (p->coef+q->coef==0) { temp=p; p=p->next; free(temp); temp=q; q=q->next; free(temp); (x->exp)--; (x->exp)--; } else { sum=p->coef+q->coef; p->coef=sum; tail->next=p; tail=p; p=p->next; temp=q; q=q->next; free(q); (x->exp)--; } } } if (p==NULL) tail=q; else tail=p; return x; } int main() { node *a,*b; a=(node *)malloc(sizeof(node)); b=(node *)malloc(sizeof(node)); a=listcreat(); b=listcreat(); a=add(a,b); cout<<a->exp; if (a->exp==0) { cout <<endl; return 0; } a=a->next; while (a!=NULL) { cout <<" "<<a->exp<<" "; cout<<a->coef; a=a->next; } cout <<endl;//} return 0; }