多项式加法
void add(NodePtr paraList1,NodePtr paraList2){
NodePtr p,q,r,s;
p=paraList1->next;
q=paraList2->next;
r=paraList1;
free(paraList2);
while((p!=NULL)&&(q!=NULL)){
if(p->exponent<q->exponent){
r->next=p;
r=p;
p=p->next;
}
else if(p->exponent>q->exponent){
r->next=q;
r=q;
q=q->next;
}
else{
p->coefficient=p->coefficient+q->coefficient;
if(p->coefficient==0){
s=p;
p=p->next;
free(s);
}
else{
r->next=p;
r=p;
p=p->next;
}
s=q;
q=q->next;
free(s);
}
if(p==NULL){
r->next=q;
}
else{
r->next=p;
}
}
}
完整代码
#include<stdio.h>
#include<malloc.h>
typedef struct LinkNode{
int coefficient;
int exponent;
struct LinkNode *next;
}*LinkList,*NodePtr;
LinkList initLinkList(){
LinkList tempHeader=(NodePtr)malloc(sizeof(LinkList));
tempHeader->coefficient=0;
tempHeader->exponent=0;
tempHeader->next=NULL;
return tempHeader;
}
void printList(LinkList paraHeader){
NodePtr p=paraHeader->next;
while(p!=NULL){
printf("%d*10^%d+",p->coefficient,p->exponent);
p=p->next;
}
printf("\r\n");
}
void appendElement(LinkList paraHeader,int paracoefficient,int paraexponent){
NodePtr p,q;
p=paraHeader;
while(p->next!=NULL){
p=p->next;
}
q=(NodePtr)malloc(sizeof(LinkList));
q->coefficient=paracoefficient;
q->exponent=paraexponent;
q->next=NULL;
p->next=q;
}
void add(NodePtr paraList1,NodePtr paraList2){
NodePtr p,q,r,s;
p=paraList1->next;
q=paraList2->next;
r=paraList1;
free(paraList2);
while((p!=NULL)&&(q!=NULL)){
if(p->exponent<q->exponent){
r->next=p;
r=p;
p=p->next;
}
else if(p->exponent>q->exponent){
r->next=q;
r=q;
q=q->next;
}
else{
p->coefficient=p->coefficient+q->coefficient;
if(p->coefficient==0){
s=p;
p=p->next;
free(s);
}
else{
r->next=p;
r=p;
p=p->next;
}
s=q;
q=q->next;
free(s);
}
if(p==NULL){
r->next=q;
}
else{
r->next=p;
}
}
}
void test(){
LinkList tempList1=initLinkList();
appendElement(tempList1,3,0);
appendElement(tempList1,3,3);
appendElement(tempList1,7,5);
appendElement(tempList1,12,10);
appendElement(tempList1,5,15);
printList(tempList1);
LinkList tempList2=initLinkList();
appendElement(tempList2,5,1);
appendElement(tempList2,-3,3);
appendElement(tempList2,2,5);
appendElement(tempList2,10,9);
appendElement(tempList2,8,15);
printList(tempList2);
add(tempList1,tempList2);
printList(tempList1);
}
int main(){
test();
}
运行结果
3*10^0+3*10^3+7*10^5+12*10^10+5*10^15+
5*10^1+-3*10^3+2*10^5+10*10^9+8*10^15+
3*10^0+5*10^1+9*10^5+10*10^9+12*10^10+13*10^15+