头文件实现:
#ifndef POLYLIST_H
#define POLYLIST_H
//Data Type
#define NULL 0
typedef enum{
_FALSE = 0,
_TRUE
}_BOOL;
typedef struct Polynode{
int coef;//系数
int exp; //指数
struct Polynode* next;
}Polynode,*Polylist;
//Function
void InputData(int* pc,int* pe);
Polylist CreatePoly();
void AddPoly(Polylist polya,Polylist polyb);
#endif
源文件实现:
#include "Polylist.h"
#include <stdio.h>
#include <stdlib.h>
void InputData(int* pc,int* pe)
{
printf("coef=");
scanf("%d",pc);
printf("exp=");
scanf("%d",pe);
}
Polylist CreatePoly()
{
Polynode *head,*tail,*s;
int c,e;
head = (Polynode*)malloc(sizeof(Polynode));//头结点
tail = head; //尾节点
InputData(&c,&e); //分别输入系数、指数
while(c)
{
s = (Polynode*)malloc(sizeof(Polynode));
s->coef = c;
s->exp = e;
tail->next = s;
tail = s; //tail始终指向尾节点
InputData(&c,&e);
}
tail->next = NULL;
return head;
}
void AddPoly(Polylist polya,Polylist polyb)
{
Polynode *p,*q,*tail,*temp;
int sum;
p = polya->next;//指向链表的第一个节点
q = polyb->next;//指向链表的第一个节点
tail = polya; //tail指向和多项式的尾节点
while(p&&q)
{
if(p->exp < q->exp)
{
tail->next = p;
tail = p;
p = p->next;
}
else if(p->exp == q->exp)
{
sum = p->coef + q->coef;
if(sum)
{
p->coef = sum;
tail->next = p;
tail = p;
p = p->next;
temp = q; q = q->next; free(temp);
}
else
{
temp = p; p = p->next; free(temp);
temp = q; q = q->next; free(temp);
}
}
else
{
tail->next = q;
tail = q;
q->next;
}
}
if(p)
tail->next = p;
else
tail->next = q;
}
//测试
int main(int argc,char* argv[])
{
Polylist pa = CreatePoly();
Polylist pb = CreatePoly();
AddPoly(pa,pb);
return 0;
}