C++版本
tip:注意最后一个测试点,需要打换行;
#include <stdio.h>
#include <stdlib.h>
//带头链表
typedef struct LNode* ptr;
typedef int Elem;
typedef struct LNode{
Elem coe;
Elem ex;
ptr Next;
}LNode;
typedef ptr Link;
Link Add(Link a,Link b);
Link Mul(Link a,Link b);
Link Mul(Link a,LNode);
Link Init();
void output(Link a);
int main(){
Link a,b;
a = Init();
b = Init();
output(Mul(a,b));
output(Add(a,b));
}
Link Init(){
int n;
scanf("%d",&n);
Link h = (Link)malloc(sizeof(struct LNode));
h->Next = NULL;
Link r = h;
while(n--){
Elem coe,ex;
scanf("%d%d",&coe,&ex);
Link s = (Link)malloc(sizeof(struct LNode));
s->coe = coe;
s->ex = ex;
r->Next = s;
r = s;
}
r->Next = NULL;
return h;
}
Link Mul(Link a,Link b){
Link h = (Link)malloc(sizeof(struct LNode));
h->Next = NULL;
Link t2 = b->Next;
while(t2){
Link tp = Mul(a,*t2);
h = Add(h,tp);
t2 = t2->Next;
}
return h;
}
Link Mul(Link a,LNode b){ //传入两个指针,第一个为头指针,第二个为元素指针
Link h =(Link)malloc(sizeof(struct LNode)),s;
Link p = a->Next;
Link r = h;
h->Next = NULL;
while(p){
s =(Link)malloc(sizeof(struct LNode));
s->coe = p->coe * b.coe;
s->ex = p->ex + b.ex;
r->Next = s;
r = s;
p = p->Next;
}
r->Next = NULL;
return h;
}
Link Add(Link a,Link b){
Link h,t1,t2,r,s; //r尾指针,s为临时指针
h = (Link)malloc(sizeof(struct LNode));
h->Next = NULL;
r = h;
t1 = a->Next;
t2 = b->Next;
while(t1 && t2){
s =(Link)malloc(sizeof(struct LNode));
if(t1->ex > t2->ex){
r->Next = t1;
r = t1;
t1 = t1->Next;
}
else if(t2->ex > t1->ex){
r->Next = t2;
r = t2;
t2 = t2->Next;
}
else {
if( t2->coe + t1->coe != 0){ s->coe=t2->coe + t1->coe ; s->ex = t1->ex ;r->Next = s ; r = s;}
t1 = t1->Next;
t2 = t2->Next;
}
}
if(t1) r->Next = t1;
else r->Next = t2;
return h;
}
void output(Link h){
Link p = h->Next;
if(!p) printf("0 0\n");
else{
while(p){
if(p->Next)printf("%d %d ",p->coe,p->ex);
else printf("%d %d\n",p->coe,p->ex);
p = p->Next;
}
}
}