typedef struct Node{
//系数
int coef;
//指数
int index;
struct Node *next;
}Node,*pNode;
pNode CreateList(int len){
pNode head,tail,new;
head = (pNode)malloc(sizeof(Node));
tail=head;
tail->next=NULL;
int coef,index;
for (int i =0; icoef=coef;new->index=index;
new->next=NULL;
tail->next=new;
tail=new;
}
return head;
}
pNode MergeList(pNode L1,pNode L2){
pNode head,tail,new;
pNode temp1,temp2;
head=(pNode)malloc(sizeof(Node));
head->next=NULL;
tail=head;
temp1=L1->next;
temp2=L2->next;
while (temp1!=NULL && temp2!=NULL) {
new=(pNode)malloc(sizeof(Node));
if(temp1->index== temp2->index){
new->index=temp1->index;
new->coef=temp1->coef+temp2->coef;
temp1=temp1->next;
temp2=temp2->next;
new->next=NULL;
tail->next=new;
tail=new;
continue;
}
if(temp1->index>temp2->index){
new->index=temp1->index;
new->coef=temp1->coef;
temp1=temp1->next;
}else{
new->index=temp2->index;
new->coef=temp2->coef;
temp2=temp2->next;
}
new->next=NULL;
tail->next=new;
tail=new;
}
while (temp1!=NULL) {
new=(pNode)malloc(sizeof(Node));
new->index=temp1->index;
new->coef=temp1->coef;
new->next=NULL;
tail->next=new;
tail=new;
temp1=temp1->next;
}
while (temp2!=NULL) {
new=(pNode)malloc(sizeof(Node));
new->index=temp1->index;
new->coef=temp1->coef;
new->next=NULL;
tail->next=new;
tail=new;
temp2=temp2->next;
}
return head;
}
void TraverseList(pNode L){
pNode p=L->next;
while(p!=NULL){
printf("%d--%d ",p->coef,p->index);
p=p->next;
}
printf("\n");
}
int main(){
int len1,len2;
pNode L1,L2,L3;
printf("input L1 len:");
scanf("%d",&len1);
L1=CreateList(len1);
printf("input L2 len:");
scanf("%d",&len2);
L2=CreateList(len2);
TraverseList(L1);
TraverseList(L2);
L3=MergeList(L1, L2);
TraverseList(L3);
}