先上代码:多项式加法
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define overflow 1
#define MAXSIZE 11
typedef struct LinkNode_{
int coefficient;
int exponent;
struct LinkNode_ *next;
} LinkNode,*linkNode;
linkNode initLinkList(){
linkNode head=(linkNode)malloc(sizeof(LinkNode));
head->coefficient=0;
head->exponent=0;
head->next=NULL;
return head;
}
void printLinkList(linkNode head){
if (!head){
printf("链表不存在.");
exit(overflow);
}
for (linkNode p=head->next;p;p=p->next){
printf("%dx^%d",p->coefficient,p->exponent);
//判断是否为最后一个
if (p->next){
//判断符号
if (p->next->coefficient>0){
printf("+");
}
}
}
printf("\n");
}
void appendElement(linkNode &head,int coe,int exp){
linkNode p=(linkNode)malloc(sizeof(LinkNode));
p->coefficient=coe;
p->exponent=exp;
p->next=NULL;
linkNode q=head;
while(q->next){
q=q->next;
}
q->next=p;
}
void merge(linkNode &head1,linkNode &head2){
linkNode p,q,r;
p=head1->next;
q=head2->next;
r=head1;
while(q!=NULL && p!=NULL){
if (q->exponent>p->exponent){
p=p->next;
r=r->next;
}
else if (q->exponent==p->exponent){
//当相加值为0,直接删除结点
linkNode s;
p->coefficient=p->coefficient+q->coefficient;
if (p->coefficient==0){
r->next=p->next;
s=p;
p=p->next;
free(s);
}
else{
p=p->next;
r=r->next;
}
s=q;
q=q->next;
free(s);
}
else{
r->next=q;
r=q;
q=q->next;
r->next=p;
}
}
if (q!=NULL)
r->next=q;
}
void Testsample(){
linkNode head1,head2;
head1=initLinkList();
head2=initLinkList();
appendElement(head1, 7, 0);
appendElement(head1, 3, 1);
appendElement(head1, 9, 8);
appendElement(head1, 5, 17);
printLinkList(head1);
appendElement(head2, 8, 1);
appendElement(head2, 22, 7);
appendElement(head2, -9, 8);
printLinkList(head2);
merge(head1,head2);
printLinkList(head1);
}
int main(void)
{
Testsample();
return 0;
}
运行结果:
7x^0+3x^1+9x^8+5x^17
8x^1+22x^7-9x^8
7x^0+11x^1+22x^7+5x^17
总结:
不算难,但是要注意判断符号,另外当和系数为0时记得删掉